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
You can do like this in more natural way,
It's called
case
and it works like you would expect, plus lots more fun stuff courtesy of===
which implements the tests.Now for some fun:
And it turns out you can also replace an arbitrary if/else chain (that is, even if the tests don't involve a common variable) with
case
by leaving out the initialcase
parameter and just writing expressions where the first match is what you want.Depending on your case, you could prefer to use a hash of methods.
If there is a long list of when's and each of them has a concrete value to compare with (not an interval), it will be more effective to declare a hash of methods and then to call the relevant method from the hash like that.