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

case / when

In this page:

  1. case / when

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
🔒

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.