Like any language, Ruby provides case statements to test multiple conditions. It is similar to the if else if else conditional statement.
It is similar to Switch in another programming language.
How to write a switch case in Ruby?
Switch executes expression and matches result with case constants and executes case block statements.
Here is the syntax of case conditions in Ruby.
case conditional_expression
when condition1
// statements;
when condition2
// statements
else
//statements;
end
conditional_expression is evaluated to value, value is compared with expression in a when and matched when statements are executed.
conditional_expression can be a variable ruby expression or enum values.
if no matching case is found, the else is executed.
expressions in when are single or multiple expressions
Here is an example case where the example
number = 19
case number
when 0 .. 9
puts "Single-digit"
when 10 .. 99
puts "Double Digits"
when 100 .. 999
puts "three digits"
when 1000 .. 9999
puts "four digits"
else
puts "five digits or more"
end
Output:
Double Digits
The above is similar to if else if else if else end conditional expressions.
Important points
- Ruby does not have a fallback or default case
- There is no break keyword
- Expression in this case is optional
- Expression in this case can be a variable, constant literal, or ruby expression
- Expression in when can be a ruby expression or multiple expressions using a logical operator