2016-11-20 174 views
2

我有一個快速的問題:評估多個條件

在Ruby中,如果我寫

def test 
    foo && a == b && c == "bar" 
end 

如果foo是空還是假的,就要保守計算表達式的休息嗎?

它是否在改變什麼,如果我這樣做,而不是

def test 
    a == b && c == "bar" if foo 
end 

非常感謝

+0

沒有,用'&&鏈的每條語句'必須是真實的。如果「foo」無或錯,則表達式的其餘部分將被忽略。 –

+0

布爾表達式總是從左到右進行計算。如果第一個條件爲假,並且您使用&&,則不會執行進一步的評估。 –

+0

好吧,所以兩個語句都是相同的情況下,foo爲空或錯誤?對 ? –

回答

1

「FOO如果爲空或假的,就要保守計算表達式的休息嗎?」 不,它不會

此表可幫助您在這樣的問題:

下表是按降序優先級(在頂部最高優先級)

N A M Operator(s)   Description 
- - - -----------   ----------- 
1 R Y ! ~ +     boolean NOT, bitwise complement, unary plus 
           (unary plus may be redefined from Ruby 1.9 with [email protected]) 

2 R Y **      exponentiation 
1 R Y -      unary minus (redefine with [email protected]) 

2 L Y */%     multiplication, division, modulo (remainder) 
2 L Y + -     addition (or concatenation), subtraction 

2 L Y << >>     bitwise shift-left (or append), bitwise shift-right 
2 L Y &      bitwise AND 

2 L Y |^     bitwise OR, bitwise XOR (exclusive OR) 
2 L Y < <= >= >    ordering 

2 N Y == === != =~ !~ <=> equality, pattern matching, comparison 
           (!= and !~ may not be redefined prior to Ruby 1.9) 

2 L N &&      boolean AND 
2 L N ||      boolean OR 

2 N N .. ...     range creation (inclusive and exclusive) 
           and boolean flip-flops 

3 R N ? :     ternary if-then-else (conditional) 
2 L N rescue     exception-handling modifier 

2 R N =      assignment 
2 R N **= *= /= %= += -=  assignment 
2 R N <<= >>=    assignment 
2 R N &&= &= ||= |= ^=  assignment 

1 N N defined?    test variable definition and type 
1 R N not     boolean NOT (low precedence) 
2 L N and or     boolean AND, boolean OR (low precedence) 
2 N N if unless while until conditional and loop modifiers 
有序
+0

我覺得比答案更需要「否」。由於這個問題只涉及'&&',爲什麼要呈現表格呢? –

4

理論

&&是一部慵懶的歌劇tor,就像||

這意味着,在a && b,如果a是假的或零,紅寶石不會刻意去檢查b因爲a && b會是假的/無反正。

這種行爲實際上是需要的,因爲它節省了時間並且可以避免NoMethodErrors。

if a && method_which_requires_a_non_nil_parameter(a) 
    # ... 
end 

method_which_requires_a_non_nil_parameter不會在所有如果a是零被調用。

或:

x = x || long_method_to_calculate_x 

通常用於高速緩存,更經常寫成:

@x ||= long_method_to_calculate_x 

回答
def test 
    foo && a == b && c == "bar" 
end 

表達的其餘部分將不會被如果評價foo是無或假的: a,b,c甚至可以是未定義的,而不會引發NameError。

def test 
    a == b & c == "bar" if foo 
end 
  • 如果foo是truthy,結果將是完全一樣的。

  • 如果foo爲零或爲假,則不會評估2個等式,就像第一個示例一樣。但是:

    • 如果foo爲零,則兩個測試都將返回nil。

    • 如果foo爲false,則第一個示例將返回false,第二個示例將返回nil。