The Ruby Case Statement a.k.a the Switch Statement: Lesson 8 of My Self-Inflicted Crash Course into Ruby

Most developers are aware of the Switch statement that compares a variable to specific cases and performs logic based on if it matches the case criteria. In Ruby they decided to implement this as simply a Case statement with when clauses specifying logic to be performed if the when clause is true.

case year
when 2000
    puts "The world was supposed to end this year!"
when 2012
    puts "Now the world is supposed to end this year!"
    puts "I wonder what year the world will supposed to end after 2012?"

As you can see from the above example it functions the same as in other languages with a slightly different syntax where instead of default you use end and instead of cases you use when

Case statements with multi value When Clauses

In Java, PHP and other programming languages the case statements can fall through so that you can define some logic to occour for multiple values. Ruby is no different in that it too allows you to have multiple values in each when statement the difference is you simply sperate the values by a ,(comma) when defining your when statements.

case year
when 2000, 2012
    puts "The world is going to end!"
    puts "Is the world going to end?"

Case statement with no value defined

If you simply prefer to write case statements instead of if statements then you can define a case statement that has no value and instead can specify the comparison logic in each when clause.

aString = "testing"

when aString="testing"
    puts "What are you testing."
    puts "This is for real everyone!"

The Case statement in Ruby breaks no new ground however it does provide you with an alternative method of writing your basic if statements. Good to know but as for which you should utilize it is really up to your own preference.

// Ruby //

Comments & Questions

Add Your Comment