← Back to Ruby Course | Chapter 6: Control Flow | Lesson 3 of 7

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:

  1. case / when
Syntax
ruby
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

markup
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
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
  1. Using case with = or == inside when, as in when value == 1, when it compares the value with === automatically.
  2. Expecting a when to fall through to the next one like in C, when only the first match runs.
  3. Forgetting else, so an unmatched value gives nil silently.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.