2016-11-20 104 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。