Changes

The Ruby case Statement

614 bytes added, 02:10, 20 November 2007
no edit summary
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 the optional ''result''variable.
Finally, The ''else'' statement specifies the default result to be returned if no match is found.
The Prius is made by Unknown
</pre>
 
== Number Ranges and the case statement ==
 
The case statement is also particularly useful when used in conjunction with number ranges (for details of ranges read the [[Ruby Ranges]] chapter of this book.
 
The following ''case'' example detects which where a number falls amongst a group of different ranges:
 
<pre>
score = 70
 
result = case score
when 0..40: "Fail"
when 41..60: "Pass"
when 61..70: "Pass with Merit"
when 71..100: "Pass with Distinction"
else "Invalid Score"
end
 
puts result
</pre>
 
The above code, when executed will result in a "Pass with Merit" message.
== Summary ==
The ''if .. else ...'' approach to building conditional logic into an application works fine for evaluating a limited number of possible criteria. For much larger evaluations, the Ruby ''case'' statement is a less cumbersome alternative. In the chapter we have looked at the case statement and reviewed some examples using strings and number ranges.