Difference between “and” and && in Ruby?

前端 未结 7 1210
别跟我提以往
别跟我提以往 2020-11-22 09:28

What is the difference between the && and and operators in Ruby?

相关标签:
7条回答
  • 2020-11-22 09:56

    || and && bind with the precedence that you expect from boolean operators in programming languages (&& is very strong, || is slightly less strong).

    and and or have lower precedence.

    For example, unlike ||, or has lower precedence than =:

    > a = false || true
     => true 
    > a
     => true 
    > a = false or true
     => true 
    > a
     => false
    

    Likewise, unlike &&, and also has lower precedence than =:

    > a = true && false
     => false 
    > a
     => false 
    > a = true and false
     => false 
    > a
     => true 
    

    What's more, unlike && and ||, and and or bind with equal precedence:

    > !puts(1) || !puts(2) && !puts(3)
    1
     => true
    > !puts(1) or !puts(2) and !puts(3)
    1
    3
     => true 
    > !puts(1) or (!puts(2) and !puts(3))
    1
     => true
    

    The weakly-binding and and or may be useful for control-flow purposes: see http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ .

    0 讨论(0)
提交回复
热议问题