Ruby uses the case keyword for switch statements.
As per the Ruby Docs:
Case statements consist of an optional condition, which is in the position of an argument to
case, and zero or morewhenclauses. The firstwhenclause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed. The value of the case statement is the value of the successfulwhenclause, ornilif there is no such clause.A case statement can end with an
elseclause. Eachwhena statement can have multiple candidate values, separated by commas.
Example:
case x
when 1,2,3
puts "1, 2, or 3"
when 10
puts "10"
else
puts "Some other number"
end
Shorter version:
case x
when 1,2,3 then puts "1, 2, or 3"
when 10 then puts "10"
else puts "Some other number"
end
The value of the case clause is matched with each when clause using the === method (not ==). Therefore it can be used with a variety of different types of objects.
A case statement can be used with Ranges:
case 17
when 13..19
puts "teenager"
end
A case statement can be used with a Regexp:
case "google"
when /oo/
puts "word contains oo"
end
A case statement can be used with a Proc or lambda:
case 44
when -> (n) { n.even? or n < 0 }
puts "even or less than zero"
end
A case statement can be used with Classes:
case x
when Integer
puts "It's an integer"
when String
puts "It's a string"
end
By implementing the === method you can create your own match classes:
class Empty
def self.===(object)
!object or "" == object
end
end
case ""
when Empty
puts "name was empty"
else
puts "name is not empty"
end
A case statement can be used without a value to match against:
case
when ENV['A'] == 'Y'
puts 'A'
when ENV['B'] == 'Y'
puts 'B'
else
puts 'Neither A nor B'
end
A case statement has a value, so you can use it as a method argument or in an assignment:
description = case 16
when 13..19 then "teenager"
else ""
end