2011-06-07 24 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