DEV Community

loading...

Case / Switch Statement in Ruby

Konnor Rogers
Full stack ruby on rails web developer
・1 min read

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

Syntax for a case statement is as follows:

case argument
when condition
  # do stuff
else
  # do stuff if nothing else meets the condition
end
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!"
else
  puts "Theres no blah here!"
end
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."
  end
end
Enter fullscreen mode Exit fullscreen mode

One liners

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

if / else syntax

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

Further Reading

https://www.rubyguides.com/2015/10/ruby-case/

https://ruby-doc.org/core-2.7.3/doc/syntax/control_expressions_rdoc.html#label-case+Expression

Discussion (2)

Collapse
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.

Collapse
djuber profile image
Daniel Uber

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