Readonly Readonly - 3 months ago 6
Ruby Question

How to write a switch statement in Ruby

How do I write a switch statement in Ruby?

Answer

Ruby uses the case expression instead.

puts case a
when 1..5
  "It's between 1 and 5"
when 6
  "It's 6"
when String
  "You passed a string"
else
  "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.

You can check more of the same from Ruby case SO Documentation

Comments