Ruby is one of the popular programming languages which was developed by Yukihiro Matsumoto in the mid-1990s. Ruby is a general-purpose language and is easy to learn. So, today we will be talking about the top 14 most asked questions about Ruby.
So, let’s get started.
Answer:
You can use
[case](http://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#S5)
expression.
<code> case<span class="pln"> x
</span> when 1. . 5
"It's between 1 and 5"
when 6
"It's 6"
when "foo" , "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."
end</code>
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 havefall-through, so there is no need to end eachwhen
with abreak
. You can also specify multiple matches in a singlewhen
clause likewhen "foo", "bar"
.
Alternative Answer:
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:
<code> 1 === 1 ## => true
Fixnum === Fixnum ## => false</code>
This means that if you want to do a
case ... when
over an object’s class, this will not work:
<code> obj = 'hello'
case obj . class
when String<span class="pln">
print</span> ( 'It is a string' )
when Fixnum<span class="pln">
print</span> ( 'It is a number' )
else<span class="pln">
print</span> ( 'It is not a string or number' )
end</code>
Will print “It is not a string or number”.
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:
<code> Fixnum === 1 ## => true</code>
In short, the code above can be fixed by removing the
.class
:
#ruby #coding #programming #programming-tips #guide-to-ruby #tutorial #latest-tech-stories