tags:

views:

3141

answers:

2

How do you write a switch statement in Ruby?

+3  A: 

it is done by case in Ruby. Also see this one.

動靜能量
+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
You can also test using regexes, which I find really useful.
Xiong Chiamiov