How do I write a switch statement in Ruby?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
- ruby - simplify string multiply concatenation
I've started to use:
It helps compact code in some cases.
Multi-value when and no-value case:
And a regular expression solution here:
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"
.case...when
behaves a bit unexpectedly when handling classes. This is due to the fact that it uses the===
operator.That operator works as expected with literals, but not with classes:
This means that if you want to do a
case ... when
over an object's class, this will not work:Will print "It is not a string".
Fortunately, this is easily solved. The
===
operator has been defined so that it returnstrue
if you use it with a class and supply an instance of that class as the second operand:In short, the code above can be fixed by removing the
.class
:I hit this problem today while looking for an answer, and this was the first appearing page, so I figured it would be useful to others in my same situation.
It is done by case in Ruby. Also see this article on Wikipedia.
Quoted:
Another example:
On around page 123 (I am using Kindle) of The Ruby Programming Lanugage (1st Edition, O'Reilly), it says the
then
keyword following thewhen
clauses can be replaced with a newline or semicolon (just like in theif then else
syntax). (Ruby 1.8 also allows a colon in place ofthen
... But this syntax is no longer allowed in Ruby 1.9.)Since
switch case
always returns a single object, we can directly print its result: