How do I write a switch
statement in Ruby?
Ruby – How to write a switch statement in Ruby
conditional-statementsrubyswitch statement
Related Topic
- C++ – Why can’t variables be declared in a switch statement
- Java – Why can’t I use switch statement on a String
- Ruby-on-rails – How to understand nil vs. empty vs. blank in Ruby
- Ruby – How to convert a string to lower or upper case in Ruby
- Ruby-on-rails – How to get the current absolute URL in Ruby on Rails
- Ruby – How to write to file in Ruby
- Ruby – attr_accessor in Ruby
- Javascript – Switch statement for multiple cases in JavaScript
Best Answer
Ruby uses the
case
expression instead.Ruby compares the object in the
when
clause with the object in thecase
clause using the===
operator. For example,1..5 === x
, and notx === 1..5
.This allows for sophisticated
when
clauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.Unlike
switch
statements in many other languages, Ruby’scase
does not have fall-through, so there is no need to end eachwhen
with abreak
. You can also specify multiple matches in a singlewhen
clause likewhen "foo", "bar"
.