Getting the control variable from switch statement
the basic syntax of switch statement in ruby开发者_Python百科 is
case expression
when condition1
statements1
when condition2
statements2
else
statements
end
Is there a way to get control expression value in statements?
Means, is there some variable which stores expression value which can be used directly - and expression need not be called again in statements body?
There is no magic variable. It's no trouble to use an ordinary variable:
case a = expensive_method
when condition1
puts "#{a} meets condition 1"
when condition2
puts "#{a} meets condition 2"
end
No, there isn't. But you can just do this:
case var = expression
when condition1
statements1
when condition2
statements2 # use var whenever you like..
else
statements
end
It's straightforward to assign the variable yourself inline:
case result = expression
when condition1
result + 1
when condition2
result + 2
else
result
end
精彩评论