Ruby Case

[Solved] Ruby Case | Ruby - Code Explorer | yomemimo.com
Question : ruby case statement

Answered by : mysterious-mantis-2t9yeiqzzhwz

# Five techniques (param, no param, regex, when/then, *array)
# With paramater
value=88
case value
when 1 puts "Single value"
when 2, 3, 4 puts "One of comma-separated values"
when 5..7 puts "One of 5, 6, 7"
when 7...10 puts "One of 8, 9, but not 10"
when "foo", "bar" puts "It's either foo or bar"
when String puts "You passed a string"
when ->(x) { x % 2 == 0 } puts "Even number (found this using lambda)"
else puts "Something else"
end
# Without paramater
value=4
case
when value < 3 puts "Less than 3"
when value == 3 puts "Equal to 3"
when (1..10) === value puts "Something in closed range of [1..10]"
end
# Using regular expressions
input = "hello 123"
case
when input.match(/\d/) puts 'String has numbers'
when input.match(/[a-zA-Z]/) puts 'String has letters'
else puts 'String has no numbers or letters'
end
# When/Then single line calls
score = 70
case score
when 0..40 then puts "Fail"
when 41..60 then puts "Pass"
when 61..70 then puts "Pass with Merit"
when 71..100 then puts "Pass with Distinction"
else "Invalid Score"
end
# Find element in array
element = 3
array = [1, 2, 3, 4, 5]
case element
when *array puts 'found in array'
else puts 'not found in array'
end

Source : https://stackoverflow.com/questions/948135/how-to-write-a-switch-statement-in-ruby | Last Update : Mon, 21 Nov 22

Question : ruby case statement

Answered by : polytrope

case {condition}
when {option1} #do something
when {option2} #do something
else #default #do something else
end

Source : | Last Update : Tue, 03 Mar 20

Question : ruby case

Answered by : lior

case fruit
when 'Apple' # something
when 'Banana' then puts 'Right' # only if it is one line
else #default # something
end

Source : | Last Update : Wed, 13 Jan 21

Question : ruby case syntax

Answered by : you

# Example 1
value = "apple"
case value
when "apple" puts "It's a fruit"
when "carrot" puts "It's a vegetable"
else puts "Unknown"
end

Source : | Last Update : Tue, 19 Sep 23

Question : ruby switch case

Answered by : you

# Sample input
color = "green"
# Using case-when
case color
when "red" puts "The color is red"
when "blue" puts "The color is blue"
when "green" puts "The color is green"
else puts "The color is unknown"
end

Source : | Last Update : Mon, 18 Sep 23

Answers related to ruby case

Code Explorer Popular Question For Ruby