The Ruby case Statement

From Techotopia
Revision as of 01:55, 20 November 2007 by Neil (Talk | contribs) (New page: In the previous chapter we looked at some basic conditional structures using the ''if ... else'' and ''if .. elsif ...'' mechanisms. These approaches to building conditional logic work wel...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In the previous chapter we looked at some basic conditional structures using the if ... else and if .. elsif ... mechanisms. These approaches to building conditional logic work well if you need to check a value against a only few different criteria (for example checking the value of a string against a couple of possible candidates):

if customerName == "Fred"
      print "Hello Fred!"
elsif customerName == "John"
      print "Hello John!" 
elsif customername == "Robert"
      print "Hello Bob!"
end

This can quickly become cumbersome, however, when a need arises to evaluate a large number of conditions. A much easier way to handle such situations is to use the Ruby case statement, the syntax for which is defined as follows:

result = case value    when match1: result1    when match2: result2'    when match3: result3'    when match4: result4'    when match5: result5'    when match6: result6'    else match7: result7' end </pre>

There can be any number of when statements - basically as many as you need to fully compare the value in the case statement against the possible options (represented by match1 through to match7 in the above example) specified by the when statements. When a match is found the result is assigned to result.

Finally, The else statement specifies the default result to be returned if no match is found.

This concept is, perhaps, best explained using an example. The following Ruby case statement is designed to match a particular car model with a manufacturer. Once a match is found, the car and associated manufacturer are included in an output string:

car = "Patriot"

manufacturer = case car
   when "Focus": "Ford"
   when "Navigator": "Lincoln"
   when "Camry": "Toyota"
   when "Civic": "Honda"
   when "Patriot": "Jeep"
   when "Jetta": "VW"
   when "Ceyene": "Porsche"
   when "Outback": "Subaru"
   when "520i": "BMW"
   when "Tundra": "Nissan"
   else "Unknown"
end

puts "The " + car  + " is made by "  + manufacturer

When executed, the resulting output will read:

The Patriot is made by Jeep

If no match was found in the case statement, then the default result, defined by the else statement would cause the following output to be generated:

The Prius is made by Unknown