The Ruby Case Statement Cheatsheet
1 min readAug 7, 2018
The Ruby case statement is simple enough to master:
case a
when 'A', 'B'
puts 'A or B'
when 'C'
puts 'A or B'
else
puts 'Not A, B, or C'
endWhen using regex (via documentation):
case "12345"
when /^1/
puts "the string starts with one"
else
puts "I don't know what the string starts with"
endWhen you want to create more complex statements (via documentation):
a = 2case
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
You can also use a lambda in when for readability:
case a
when ->(n){n == 1 || n == 2}
puts "a is one or two"
when when ->(n){n <= 3}
puts "a is at least 3"
else
puts "I don't know what a is"
endThings to note:
- The
,inwhen 'A', or 'B'means “or” - The default block is under
else whencan accept regex or procs. For a full list of things you can do withwhensee things you can do===.
