How do you write a switch statement in Ruby?
+21
A:
Ruby uses the case statement instead.
case a
when 1..5
puts "It's between 1 and 5"
when 6
puts "It's 6"
when String
puts "You passed a string"
else
puts "You gave me #{a} -- I have no idea what to do with that."
end
The comparison is done by comparing the object in the when-clause with the object in the case-clause using the ===
operator. That is, it does 1..5 === a
and String === a
, not a === 1.5
. This allows for the sophisticated semantics you see above, where you can use ranges and classes and all sorts of things rather than just testing for equality.
Chuck
2009-06-04 01:22:57
You can also test using regexes, which I find really useful.
Xiong Chiamiov
2010-08-28 00:43:10