case / when
In this page:
case / when
A case statement compares a value against a series of when patterns, running the block for the first match -- Ruby's equivalent of switch statements in other languages, but with more powerful matching. when uses the === operator internally, which lets patterns match by class, range, or regex, not just equality. else handles anything not matched by an earlier when.
Note: when can match a Class, a Range, or a Regexp, not just an exact value -- case x; when Integer then ... works.
Example: case / when
value = 42
case value
when 1..10
puts "Small number"
when 11..100
puts "Medium number"
else
puts "Large number"
end
case value
when String
puts "It's a string"
when Integer
puts "It's an integer"
end
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: