# Ruby's Switch Statement is More Flexible Than You Thought

*Published on April 25, 2023*

---


Here's the standard version of the switch statement in Ruby.

```ruby
season = 'winter'

case season
when 'summer'
  puts 'it is warm'
when 'winter'
  puts 'it is cold'
else
  puts 'it is raining'
end

# output
# it is cold
```

In typical Ruby style of developer happiness, it's called&nbsp;`case`&nbsp;and&nbsp;`when`, instead of `switch` and `case`. I find Ruby's version easier to read and understand.

_**Note: There're no**_&nbsp;_**`break`**_&nbsp;_**statements at the end of each**_&nbsp;_**`when`**_&nbsp;_**clause. Unlike other languages, Ruby's**_&nbsp;_**`case`**_&nbsp;_**doesn't fall through.**_

In the standard form, we're just comparing the expression provided to&nbsp;`case`&nbsp;with the `when` expression and executing the code provided. When no matches are found, the&nbsp;`else`&nbsp;statement is executed.

In fact, what really happens is that Ruby compares the expression value provided in the&nbsp;`when`&nbsp;clause with the value in the&nbsp;`case`&nbsp;clause using the&nbsp;`===`&nbsp;operator. This lets you do fancy (but useful) stuff like this:

```ruby
puts 'enter a number'
number = gets.to_i

case number
when 1..10
  puts 'between 1 and 10'
when 11..20
  puts 'between 11 and 20'
when 50
  puts 'exactly 50'
when 60, 70
  puts 'either 60 or 70'
else
  puts 'invalid number'
end
```

**Note: The order matters. We're comparing the expression provided to the**&nbsp;**`when`**&nbsp;**clause with the**&nbsp;**`case`**&nbsp;**expression, not the other way around (****`when === case`****, not**&nbsp;**`case === when`****). This is because Ruby actually calls the**&nbsp;**`===`**&nbsp;**method on the left operand, passing the second operand as an argument.**

The following example shows the difference.

```ruby
(1..10) === 5 # true 

5 === (1..10) # false
```

You can also shorten the code by returning on the same line as&nbsp;`when`&nbsp;clause, using the&nbsp;`then`&nbsp;clause.

```ruby
def can_drive(age)
  case age
  when 1..14 then 'no'
  when 15..100 then 'yes'
  end
end

puts can_drive(18) # yes
```

Additionally, if you want to do comparisons on a variable, just leave out the&nbsp;`case`&nbsp;expression. This helps to simplify a long and complex if-else chain.

```ruby
def calculate(num)
  case
  when num > 10
    puts 'greater than 10'
  when num == 5
    puts 'exact 5'
  end
end

calculate 12 # greater than 10
```

Pretty useful. Now, let's learn how you can match data types of objects.

## Matching Types

The&nbsp;`===`&nbsp;operator lets you match the types of objects. For example,

```ruby
Integer === 1     # true
String === 'name' # true
```

That means you can pass an object in the&nbsp;`case`&nbsp;clause and match types in the&nbsp;`when`&nbsp;clause, as follows:

```ruby
def perform(obj)
  case obj
  when String
    puts 'a string'
  when Integer
    puts 'an integer'
  when Vehicle
    puts 'a vehicle'
  else
    puts 'not a string, integer, or vehicle'
  end
end

perform 5             # an integer
perform 'name'        # a string

class Vehicle
end

perform Vehicle.new   # a vehicle
```

_**Note: Do not use**_&nbsp;_**`obj.class`**_&nbsp;_**in the**_&nbsp;_**`case`**_&nbsp;_**clause, as**_&nbsp;_**`Integer === Integer`**_&nbsp;_**returns false. This might seem strange at first, but remember that Ruby is actually calling the**_&nbsp;[_**`===`**_](https://ruby-doc.org/3.2.0/Module.html#method-i-3D-3D-3D)&nbsp;_**method on**_&nbsp;_**`Integer`**__**. This method checks if the second argument is an instance of this module. Hence it returns**_&nbsp;_**`false`**__**.**_

It's also possible to evaluate custom, complicated expressions via a lambda or even classes. Let's see how.

## Custom Expressions

> If it walks like a duck and quacks like a duck, it is a duck.

So far, we have learned that Ruby will match the&nbsp;`when`&nbsp;clause with the&nbsp;`case`&nbsp;clause using the&nbsp;`===`&nbsp;operator. In fact, it's calling the&nbsp;`===`&nbsp;method on the value returned by the&nbsp;`when`&nbsp;clause. Because of the dynamic nature of Ruby, you can pass any object that has a&nbsp;`===`&nbsp;method.

For example, a lambda has a&nbsp;[`===`](https://ruby-doc.org/3.2.0/Proc.html#method-i-3D-3D-3D)&nbsp;method which simply passes the second operand as an argument to the lambda.

```ruby
even = ->(x) { x % 2 == 0 }

even === 4  # true
even === 5  # false
```

This means that you can pass a lambda expression in the&nbsp;`when`&nbsp;clause.

```ruby
is_even = ->(x) { x % 2 == 0 }
is_odd = ->(x) { x % 2 == 1 }
num = 4

case num
when is_even then 'even'
when is_odd then 'odd'
end
```

In fact, any object that has a&nbsp;`===`&nbsp;method can be used in a&nbsp;`when`&nbsp;statement.

```ruby
num = 5

class Even
  def ===(obj)
    (obj % 2) == 0
  end
end

class Odd
  def ===(obj)
    (obj % 2) == 1
  end
end

case num
when Even.new then puts 'even'
when Odd.new then puts 'odd'
end
```

This example is not that useful as it's oversimplified. I can't think of a real-life scenario where I'd use custom classes, but it's pretty useful to know that Ruby let's you do this.

Finally, let's see how you can match regular expressions inside&nbsp;`case`&nbsp;statement.

## Match Regular Expressions

You can use the&nbsp;`===`&nbsp;operator to match a string against a regular expression.

```ruby
pattern = /hello.+/ 

pattern === 'hello world' # true
pattern === 'world'       # false
```

As a result, you can use regular expressions in the&nbsp;`when`&nbsp;clause in a&nbsp;`case`&nbsp;statement.

```ruby
case word
when /\d/
  puts 'digit'
when /[aeiou]/
  puts 'a vowel'
end
```

Couldn't get simpler than this.

## Pattern Matching

[Pattern Matching](https://ruby-doc.org/3.2.0/syntax/pattern_matching_rdoc.html)&nbsp;is another powerful use case for the case statement in Ruby (_**Credits:**_&nbsp;_Thanks to the commenter on Hackernews for pointing this out_). I recommend reading the official documentation, but here's a gist of it:

Pattern matching allows deep matching of structured values:&nbsp;**checking the structure and binding the matched parts to local variables.**&nbsp;It uses&nbsp;`case .. in`&nbsp;instead of&nbsp;`case .. when`.

```ruby
case <expression>
in <pattern1>
  ...
in <pattern2>
  ...
in <pattern3>
  ...
else
  ...
end
```

For example,

```ruby
config = {db: {user: 'admin', password: 'abc123'}}

case config
in db: {user:} # matches subhash and puts matched value in variable user
  puts "Connect with user '#{user}'"
in connection: {username: }
  puts "Connect with user '#{username}'"
else
  puts "Unrecognized structure of config"
end
# Prints: "Connect with user 'admin'"
```

It's fascinating and deserves a blog post on its own. Stay tuned!

That's a wrap.&nbsp;**Did I miss anything?**&nbsp;Please let me know in the comments below.

