Ruby's switch is case / when: case day when "Sat", "Sun" then "weekend" else "weekday" end. List several values in one when with commas, and there is no break: only the first matching branch runs. Each when tests with ===, so it also matches ranges (when 1..9), regexes (when /\A\d+\z/) and classes (when String).
A Ruby case compares one value against a list of when clauses and runs the first one that matches. It differs from the C and JavaScript switch in three ways: there is no fall-through, the whole case returns a value you can assign, and the test is not == but ===, which each class defines for itself. The sections below cover plain values and comma lists, ranges and regexes, matching on a type (and why case obj.class never matches), how === works and how to plug in your own test, case with no subject, and the case / in pattern matching that destructures arrays and hashes, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1case / when with valuesRecommended
Put the value after case and one or more candidates after each when, separated by commas. The first when with a matching candidate runs, and the rest are skipped, so you never write break. else catches everything else. For a one-line branch, put then after the candidates. A case is an expression: it returns the value of the branch that ran (or nil when nothing matched and there is no else), so you can assign it or return it from a method. To match against the values of an array, splat it into the when with *.
def describe(day) case day when "Saturday", "Sunday" "weekend" when "Friday" "almost weekend" else "weekday" end end puts describe("Sunday") puts describe("Friday") puts describe("Tuesday") # case is an expression: assign its value status = 404 message = case status when 200 then "OK" when 301, 302 then "Redirect" when 404 then "Not Found" else "Unknown" end puts message # No match and no else gives nil result = case 7 when 1 then "one" end p result # Match any value of an array: splat it VOWELS = %w[a e i o u] letter = "e" case letter when *VOWELS then puts "#{letter} is a vowel" else puts "#{letter} is a consonant" end # No fall-through: only the first matching when runs case 5 when 1..10 then puts "1..10" when 5 then puts "five" end
Output
"Sunday" matches the first when through its second candidate and prints weekend; "Tuesday" falls to else. message gets Not Found straight from the case, and the case on 7 with no else prints nil. The last block prints only 1..10: 5 also equals the second candidate, but the first match wins and nothing falls through. Python 3.10's match is closer to Ruby's case / in (section 6) than to this form.
2Ranges and regular expressions
A range in a when matches any value inside it, which turns a chain of if score >= 90 … elsif score >= 80 into one line per band. Use ... (three dots) to exclude the end, so 89.5 does not slip between 80..89 and 90... An endless range such as 90.. covers everything from 90 up. A regex in a when matches strings that contain the pattern, and a successful match sets $~ (the MatchData) and $1, $2 and so on, so the branch can use the captured groups.
def grade(score) case score when 90.. then "A" when 80...90 then "B" when 70...80 then "C" else "F" end end [95, 90, 89.5, 72, 40].each { |s| puts "#{s}: #{grade(s)}" } def kind(input) case input when /\A\d+\z/ then "number" when /\A[a-z_]\w*\z/ then "identifier" when /\A(\d{4})-(\d{2})-(\d{2})\z/ "date, year #{$1}, month #{$~[2]}" else "other" end end %w[42 user_id 2026-12-02 Hi!].each { |s| puts "#{s}: #{kind(s)}" }
Output
90 lands in A and 89.5 in B, because 80...90 holds every number below 90, fractions included. The date branch reads its groups back from the match: $1 is 2026 and $~[2] is 12. Anchor the regex with \A and \z when the whole string must match: without them, /\d+/ would also match "Hi 42".
3Match on a type: when String, not case obj.class
To branch on what kind of object you have, write case value and put class names after when. when String runs String === value, and for a class that means "is value an instance of this class or a subclass?", the same as is_a?. Modules work too (when Comparable, when Enumerable), and when nil catches nil. The common mistake is case value.class: it never matches when String, as the second half of the script shows.
def describe(value) case value when Integer, Float then "number #{value}" when String then "string of #{value.size} chars" when Array then "array of #{value.size}" when nil then "nil" else "something else: #{value.class}" end end [42, 3.5, "hello", [1, 2], nil, :sym].each { |v| puts describe(v) } # The common mistake: case value.class value = "hello" case value.class when String then puts "String" else puts "no match for #{value.class}" end # Why: when String asks String === subject p String === "hello" p String === String p Class === String
Output
describe sorts each value by its class, and :sym falls to else. The case value.class block prints no match for String even though the class is String: the subject is now the String class itself, so the test becomes String === String, which asks whether the String class is a string. It is not (false); it is a Class, which is why Class === String prints true. Drop the .class and the when String works. For more on type checks outside a case, see check a type at runtime.
4How when tests: the === operator
when x runs x === subject, with the candidate on the left. === is an ordinary method, and each class decides what it means: for most objects it is ==, for a class it is is_a?, for a range it is "inside the range", for a regex it is "the string matches", for a Set it is include?, and for a lambda or proc it calls the lambda with the subject. That last one lets you put any test in a when, and any class of your own can define === to join in. The script ends with the four equality methods side by side, since they are easy to mix up.
require 'set' # when x runs x === subject: the candidate is on the left p Integer === 5 p 5 === Integer p((1..10) === 5) p(/ell/ === "hello") # A lambda's === calls it with the subject even = ->(n) { n.even? } big = ->(n) { n > 100 } [4, 7, 250].each do |n| label = case n when big then "big" when even then "even" else "odd" end puts "#{n}: #{label}" end # A Set matches its members WEEKEND = Set["Sat", "Sun"] case "Sun" when WEEKEND then puts "Sun is in the weekend set" end # Your own class can define === class Between def initialize(low, high) @low = low @high = high end def ===(other) other.between?(@low, @high) end end TEEN = Between.new(13, 19) case 15 when TEEN then puts "15 is a teen" end # The four equality methods a = "ruby" b = "ruby" p a == b p a.eql?(b) p a.equal?(b) p 1 == 1.0 p 1.eql?(1.0)
Output
Integer === 5 is true but 5 === Integer is false: === is not symmetric, and the order in a case is always candidate first. 250 is even, yet it prints big because the big lambda comes first. In the last group, == compares values, eql? compares values and types (so 1.eql?(1.0) is false; hash keys use it), and equal? asks whether both names point to the same object, which two separately built strings do not.
5case with no subject
Leave out the value after case and each when takes a full condition instead. The first condition that is truthy wins. It is another way to write an if / elsif chain, and it reads well when the conditions test different things, so there is no single value to switch on.
def advice(temp, raining) case when raining && temp < 5 then "sleet, stay in" when raining then "take an umbrella" when temp > 25 then "hot and dry" else "a fine day" end end puts advice(2, true) puts advice(15, true) puts advice(30, false) puts advice(18, false)
Output
advice(2, true) meets both of the first two conditions and prints sleet, stay in, because the more specific test comes first; swap them and it would say take an umbrella. With no subject there is no === at all: when just evaluates the expression, so a range or a class here would always count as true.
6Pattern matching with case / in
case with in instead of when matches the shape of a value and pulls parts out into variables. It became a stable feature in Ruby 3.0. A hash pattern such as { type: "key", key: String => key } checks the keys you list and ignores any others; => name binds the matched part to a variable, and { error: } is short for binding the error key to a variable of the same name. An array pattern must match the whole array, *rest collects the remainder, and the find pattern [*, x, *] looks for one element anywhere. | gives alternatives and if after a pattern adds a guard. Unlike case / when, a case / in with no match and no else raises NoMatchingPatternError.
def handle(event) case event in { type: "click", x: Integer => x, y: Integer => y } "click at #{x},#{y}" in { type: "key", key: "q" | "Q" } "quit" in { type: "key", key: String => key } if key.size == 1 "key #{key}" in [Integer => a, Integer => b] "pair #{a + b}" in [*, { error: }, *] "error found: #{error}" in [first, *rest] "list starting #{first}, #{rest.size} more" in String | Symbol => name "name #{name}" end end puts handle({ type: "click", x: 10, y: 20, button: 1 }) puts handle({ type: "key", key: "Q" }) puts handle({ type: "key", key: "a" }) puts handle([3, 4]) puts handle([{ ok: 1 }, { error: "disk full" }, { ok: 2 }]) puts handle([1, 2, 3]) puts handle(:save) # No in matched and no else: NoMatchingPatternError begin handle({ type: "key", key: "enter" }) rescue NoMatchingPatternError => e puts "#{e.class}: #{e.message}" end
Output
The click event matches even though it has an extra button key, and x and y come out as variables. "a" passes the if key.size == 1 guard; "enter" fails it, matches nothing else, and raises NoMatchingPatternError: {type: "key", key: "enter"}, whose message is the unmatched value. [3, 4] hits the two-integer pattern, while [1, 2, 3] has three elements and goes to [first, *rest]. The find pattern sits before [first, *rest] on purpose: patterns are tried in order, and [first, *rest] matches any non-empty array.
7Which should you use?
| Form | Test it runs | Best for |
|---|---|---|
| when "a", "b" | === (== for strings, numbers) | Fixed values: most switches |
| when 80...90 | Range#===: inside the range | Number bands, grades, ages |
| when /\A\d+\z/ | Regexp#===: string matches | String shapes; sets $~ and $1 |
| when String | Module#===: is_a? | Branching on type (not case x.class) |
| when ->(x) { … } | Proc#===: calls it | Any custom test |
| case (no subject) | Truthiness of each when | Unrelated conditions, like if / elsif |
| case … in | Patterns (raises if none match) | Destructuring arrays and hashes |
Frequently asked questions
Does Ruby have a switch statement?
Yes, it is case / when: case x when 1 then "one" when 2, 3 then "few" else "many" end. There is no switch keyword, no break, and no fall-through: the first matching when runs and the rest are skipped. The whole case returns the value of that branch, so you can assign it.
How do I match several values in one when?
Separate them with commas: when "Saturday", "Sunday". The branch runs if any of them matches. If the values are in an array, splat it: when *WEEKEND_DAYS. A range such as when 1..5 covers a run of numbers in one candidate.
Why does case obj.class not match when String?
Because when String tests String === subject, and with case obj.class the subject is the class itself. String === String asks whether the String class is a string, which is false; it is a Class. Write case obj and keep when String, which tests obj.is_a?(String).
What is the difference between ==, ===, eql? and equal? in Ruby?
== compares values (1 == 1.0 is true). eql? compares values and types (1.eql?(1.0) is false), and hashes use it for keys. equal? is identity: true only for the very same object. === is the case-equality test when uses; each class defines it, as is_a? for classes, membership for ranges, a match for regexes, and a call for lambdas.
What is the difference between case/when and case/in?
case / when tests each candidate with === and returns nil when nothing matches and there is no else. case / in matches structure, binds variables (in { name: String => name }, in [first, *rest]) and raises NoMatchingPatternError when nothing matches and there is no else. Use when for plain values, ranges and classes, and in to take arrays and hashes apart.
How do I compare against a variable inside a case/in pattern?
Pin it with ^: in ^expected. A bare name in a pattern is a new variable that matches anything, so in expected would always match and overwrite expected. In case / when this does not come up: when expected already compares with the variable's value.