Ruby Case
A case statement matches one value against a list of choices. The first choice that matches runs its block.
Matching a number
The value after case is matched against each when line. The day is 3, so the third choice runs.
day = 3
case day
when 1
puts "Monday"
when 2
puts "Tuesday"
when 3
puts "Wednesday"
else
puts "Another day"
endMatching a word
A when line can name a word instead of a number. The word apple matches the first choice.
fruit = "apple"
case fruit
when "apple"
puts "Red fruit"
when "banana"
puts "Yellow fruit"
else
puts "Unknown fruit"
endTwo values on one when
A comma lets one when line hold two values. The number 2 matches the first line.
number = 2
case number
when 1, 2
puts "Low"
when 3, 4
puts "High"
endSaving the answer
The whole case statement can sit on the right side of an equals sign. Its answer is saved into label.
grade = "B"
label = case grade
when "A"
"Excellent"
when "B"
"Good"
else
"Other"
end
puts labelExample
choice = "tea"
size = 2
drink = case choice
when "tea"
"Tea"
when "coffee"
"Coffee"
else
"Water"
end
case size
when 1, 2
puts "#{drink} in a small cup"
when 3, 4
puts "#{drink} in a large cup"
endKey points
- Use case to start a match on one value.
- Use when to name a value that can match.
- One when line can list two values.
- Use else to cover a value that matches no when line.
- end closes a case statement.
- A case statement matches one value against many choices.
- The answer of a case statement can be saved into a variable.
In this example, choice holds the word tea. The first case statement matches tea and saves the word Tea into drink. The second case statement matches size, which is 2, against the line that lists 1 and 2. That block prints the drink name inside a sentence about a small cup.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
Which when line matches the value 2?