Ruby - Case Statement
The Case statement in Ruby language is used to execute one of many code statements. It can be considered as group of If-else statements.
Syntax
case expression when expression 1 [then] statement 1 when expression 2 [then] statement 2 ... ... ... when expression n [then] statement n else default statement end
The case expression is evaluated and matched with when expressions. When it matches, the following when block of code is executed.
Example:
In the example below, the case expression is a variable called i with value 2 which is matched against when expressions. When it matches with the when expression, the following block of code is executed.
i = 2 case i when 1 puts "Red" when 2 puts "Blue" when 3 puts "Green" end
The output of the above code will be:
Blue
else statement
The else Statement can also be used with case statement. It is executed when there is no match between any when expressions.
Example:
In the example below, the case expression is a variable called i with value 10 which is matched against when expressions. As there is no match, the else block of code gets executed.
i = 10 result = case i when 1 then "Red" when 2 then "Blue" when 3 then "Green" else "No match found." end puts result
The output of the above code will be:
No match found.
Common code blocks
There are instances where same code block is required in multiple when expression.
Example:
In the example below, same code block is shared for different when expressions.
i = 10 result = case i when 1 "Red" when 2, 10 "Blue" when 3, 4 "Green" end puts result
The output of the above code will be:
Blue