2011-06-07 78 views
2

switch语句的红宝石的基本语法是充分利用switch语句

case expression 
    when condition1 
    statements1 
    when condition2 
    statements2 
    else 
    statements 
end 

有没有办法让报表控制表情值的控制变量?

意思是,是否有一些变量存储可以直接使用的表达式值 - 而且表达式不需要在语句体中再次调用?

回答

3

没有魔法变量。使用普通变量并不麻烦:

case a = expensive_method 
    when condition1 
    puts "#{a} meets condition 1" 
    when condition2 
    puts "#{a} meets condition 2" 
end 
0

不,没有。但是你可以只是这样做:

case var = expression 
when condition1 
    statements1 
when condition2 
    statements2 # use var whenever you like.. 
else 
    statements 
end 
0

它的简单的可变自己直列分配:

case result = expression 
when condition1 
    result + 1 
when condition2 
    result + 2 
else 
    result 
end