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
Many programming languages, especially those derived from C, have support for the so-called Switch Fallthrough. I was searching for the best way to do the same in Ruby and thought it might be useful to others:
In C-like languages fallthrough typically looks like this:
In Ruby, the same can be achieved in the following way:
This is not strictly equivalent, because it's not possible to let
'a'
execute a block of code before falling through to'b'
or'c'
, but for the most part I find it similar enough to be useful in the same way.reference => https://www.tutorialspoint.com/ruby/ruby_if_else.htm
You can use regular expressions, such as finding a type of string:
Ruby's
case
will use the equality operand===
for this (thanks @JimDeville). Additional information is available at "Ruby Operators". This also can be done using @mmdemirbas example (without parameter), only this approach is cleaner for these types of cases.Ruby uses the
case
for writing switch statements.As per the Ruby Docs:
Example:
Shorter version:
And as this blog by Honeybadger describes Ruby Case;
Can be used with Ranges:
Can be used with Regex:
Can be used with Procs and Lambdas:
Also, can be used with your own match classes:
Lots of great answers but I thought I would add one factoid.. If you are attempting to compare objects (Classes) make sure you have a space ship method (not a joke) or understand how they are being compared
Here is a good discussion on the topic http://www.skorks.com/2009/09/ruby-equality-and-object-comparison/
No support for regular expressions in your environment? E.g. Shopify Script Editor (April, 2018):
A workaround following a combination of methods already previously covered in here and here:
I used
or
s in the class method statement since||
has higher precedence than.include?
. If you are a ruby-nazi, please imagine I used this(item.include? 'A') || ...
instead. repl.it test.