case value
when 1, 2, 5
do_this
when 3
do_that
else
do_the_other
end
In this example the first
when
will catch three different values. Note that unlike the C family of languages, there is no break statement used. Options cannot fall though to the next one.You do not need to give a parameter to the
case
statement, as seen here.case
when @t == 7
p 't is 7'
when @s == :this
p 's is :this'
else
p 'none of the above'
end
In this form, the case is like an
if/elsif
chain.if @t == 7
p 't is 7'
elsif @s == :this
p 's is :this'
else
p 'none of the above'
end
So why use case? Well, case returns a value, so instead we could do this:
s = case
when @t == 7
't is 7'
when @s == :this
's is :this'
else
'none of the above'
end
The Relationship Operator
The
case
statement uses the relationship operator, ===
(aka triple equals or trequals operator) when comparing the value to each when. The relationship operator is really a method, and in Object
the relationship operator is defined to do the same as the equals operator. However, the important point here is that it can be overridden as required. Patterns override it to check for a match, and the Range
class overrides it to check if the value is within the range. That allows you to do things like this:mark = 56
grade = case mark
when 1..25
'Fail'
when 26..50
'C'
when 51..75
'B'
when 76..100
'A'
else
'Out of range!'
end
Here grade is set to 'B' because
(51..75) === 56
evaulates to true. Note that this is calling the ===
method on 51..75
. Write it the other way around, 56 === (51..75)
, and the ===
method of 56
is invoked, and the expression evaluates to false.See more here:
http://www.pmamediagroup.com/2009/07/dont-call-it-case-equality/
Struggling with Ruby: Contents Page
No comments:
Post a Comment