How to Use Case When in Ruby: Simple Guide with Examples
In Ruby, use
case with when to check a value against multiple conditions cleanly. The syntax is case variable; when value1 then ...; when value2 then ...; else ...; end. It works like a simpler alternative to many if-elsif statements.Syntax
The case statement evaluates an expression once and compares it with each when clause. If a match is found, the corresponding code runs. The else clause is optional and runs if no matches occur.
- case expression: The value to compare.
- when value: Checks if expression equals this value.
- then: Optional keyword to put code on the same line.
- else: Runs if no
whenmatches. - end: Closes the case block.
ruby
case expression when value1 # code if expression === value1 when value2 then # code if expression === value2 else # code if no match end
Example
This example shows how to use case when to print a message based on a day of the week.
ruby
day = "Tuesday" case day when "Monday" puts "Start of the work week" when "Tuesday" puts "Second day of the week" when "Friday" puts "Almost weekend!" else puts "Just another day" end
Output
Second day of the week
Common Pitfalls
One common mistake is forgetting the end keyword to close the case block. Another is using when without a matching case. Also, case compares with ===, so be careful with types and ranges.
Example of a wrong and right way:
ruby
# Wrong: missing end # case x # when 1 # puts "One" # Right: case x when 1 puts "One" end
Quick Reference
| Keyword | Purpose |
|---|---|
| case | Starts the case statement with an expression to compare |
| when | Defines a condition to match against the case expression |
| then | Optional, separates condition and code on the same line |
| else | Runs if no when condition matches |
| end | Ends the case statement |
Key Takeaways
Use case when to simplify multiple condition checks in Ruby.
Remember to close the case block with end.
The case statement uses === for comparison, so it works with ranges and classes.
The else clause is optional but useful for default cases.
Use then for concise one-line when statements.