How to write a switch statement in ruby

case a
when 1..10
  puts "It's between 1 and 10"
when 8
  puts "It's 8"
when String
  puts "You passed a string"
else
  puts "You gave me #{a} -- I have no idea what to do with that."
end

Programming languages are very similar to spoken languages. One of the closest similarities is the translation of certain words or concepts from language to language.

In English we say “Hello” while a Spanish speaking person might say “Hola”. Generally these two definitions mean same thing and are direct translations of each other. With programming languages there are also certain concepts and definitions which are translatable from one language to the other.

I have a friend that codes in ActionSCript and he has been very helpful when I get stuck on a problem or concept in Ruby. It amazes me that he is just as able to solve a problem based in Ruby by looking at it through the eyes of his chosen language, ActionScript. Additionally a lot of times the code looks so similar that I can understand the flow even though I do not know the intricacies of ActionScript itself.

I’m finding that programming constructs are generally the same from language to language. There are certainly subtle differences between languages but the basic methods, ideas and definitions do not change much.

Last night I was working on a problem that matched round, square and curly braces. I was given an array which held string expressions of braces. A matched brace meant that the round, square and curly braces all closed perfect. As an example “([])” would be a matched brace but “[(])” would not.

I was able to setup the initial flow of the problem but got a little stuck when trying to compare the matched braces within each other. I showed the problem to my friend and he was able to come up with a solution using a switch statement. I searched online for the equivalent switch statement in Ruby and found it was the case statement. I had seen it before but never really used it extensively. It’s really useful because you can match objects to the case statement then perform an operation if it is an exact match (a == 1..10). This saves lines and times without having to write numerous if, elsif and else statements.

Using the case statement I was able to solve the problem and now have a handy new weapon in my coding arsenal. I’m going to train very hard over the next few weeks and I think I’ll be battle ready very soon.

 
0
Kudos
 
0
Kudos

Now read this

Ruby class shortcuts

class Person attr_accessor :name, :age end # same as: class Person def name @name end def name=(name) @name = name end def age @age end def age=(age) @age = age end end Ruby is awesome. I think it has to do with the ease and beauty of... Continue →