case / when
case and when compare one value against a list of options, like a vending machine matching your button. Ruby runs the block of the first option that fits.
In this page:
Syntax
case value
when pattern1
# body
when pattern2, pattern3
# body
else
# default
end
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
casewith=or==insidewhen, as inwhen value == 1, when it compares the value with===automatically. - Expecting a
whento fall through to the next one like in C, when only the first match runs. - Forgetting
else, so an unmatched value givesnilsilently.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: