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.

14 Most Asked Questions About Ruby

1. How to write a switch statement in Ruby?

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

whenclause with the object in thecaseclause using the===operator. For example,1..5 === x, and notx === 1..5.

This allows for sophisticated

whenclauses as seen above. Ranges, classes, and all sorts of things can be tested for rather than just equality.

Unlike

switchstatements in many other languages, Ruby’scasedoes not havefall-through, so there is no need to end eachwhenwith abreak. You can also specify multiple matches in a singlewhenclause likewhen "foo", "bar".

Alternative Answer:

case...whenbehaves 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            ## =&gt; true
 Fixnum  ===  Fixnum  ## =&gt; false</code>

This means that if you want to do a

case ... whenover 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 returnstrueif you use it with a class and supply an instance of that class as the second operand:

<code> Fixnum  ===  1  ## =&gt; 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

14 Ruby FAQs and Answers
1.25 GEEK