DEV Community 👩‍💻👨‍💻

Konnor Rogers
Konnor Rogers

Posted on

Case / Switch Statement in Ruby

Why is this here?

I always forget how to write case statements and always find myself looking it up. This is my note to future self on how to write case / switch statements in Ruby.


Syntax for a case statement is as follows:

case argument
when condition
  # do stuff
  # do stuff if nothing else meets the condition
Enter fullscreen mode Exit fullscreen mode

"Else" is optional and represents the "default" case.

All case statements written in this syntax are compared with the === operator so be aware of that! === has slightly different semantics from == which can be found here:

This same === feature is what allows us to compare Regexs on Strings and other cool behavior. === is overriden by individual modules but is usually aliased to ==

Basic statement

arg = "blah"
case arg
when /blah/
  puts "woah, what a blah!"
  puts "Theres no blah here!"
Enter fullscreen mode Exit fullscreen mode

Adding multiple conditionals

def fruit_identifier(fruit)
  case fruit
  when "orange", "grapefruit"
    puts "Woah! Thats some good citrus!"
  when "apple", "banana", "pear"
    puts "Just some normal fruits. Nothing to see here."
Enter fullscreen mode Exit fullscreen mode

One liners

def one_line_case
  case "only_one"
  when "only_one" then puts "Look ma! One line!"
Enter fullscreen mode Exit fullscreen mode

if / else syntax

a = 2
when a == 1, a == 2
  puts "a is one or two"
when a == 3
  puts "a is three"
  puts "I don't know what a is"
Enter fullscreen mode Exit fullscreen mode

Further Reading

Top comments (2)

polar profile image
Polar Humenn

I never understood the reason why they just did not go with a defacto standard (switch, case, default)? It is quite annoying. I have to look this up all the time when I have to write some Ruby code. Sort of like Microsoft choosing a backslash for a file separator.

djuber profile image
Daniel Uber

I also always forget how to write these and have to look it up.

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now