Readonly Readonly - 6 months ago 17
Ruby Question

How to write a switch statement in Ruby

How do I write a switch statement in Ruby?


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"
  "You gave me #{a} -- I have no idea what to do with that."

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