i = true and false in Ruby is true?

后端 未结 5 963
傲寒
傲寒 2021-01-04 05:55

Am I fundamentally misunderstanding Ruby here? I\'ve been writing Ruby code for about 2 years now and just today stumbled on this...

ruby-1.8.7-p249 > i =         


        
相关标签:
5条回答
  • 2021-01-04 06:03

    The operators && and and have different precedence, and = happens to be in between.

    irb(main):006:0> i = true and false
    => false
    irb(main):007:0> i
    => true
    irb(main):008:0> i = true && false
    => false
    irb(main):009:0> i
    => false
    irb(main):010:0> 
    

    The first is read as (i = true) and false, the second as i = (true && false).

    0 讨论(0)
  • 2021-01-04 06:06

    Your line is parsed as

    i = true and false
    (i = true) and false
    true and false
    

    And of course because of i = true, i will be true afterwards.

    0 讨论(0)
  • 2021-01-04 06:09

    and has lower precedence than = so i = true and false is parsed as (i = true) and false.

    So the value true is assigned to i and then the return value of that operation (which is true) is anded with false, which causes the whole expression to evaluate to false, even though i still has the value true.

    0 讨论(0)
  • 2021-01-04 06:11

    As I understand your code, it is interpreted as :

    • Assign true to i
    • Return i and false

    The results seems correct.

    0 讨论(0)
  • 2021-01-04 06:17

    As others have elucidated above, the keyword and is used when you want to put two different statements on one line. It is just a nicer way of making your code readable.

    Thus,

     i = true and false 

    implies

    i = true; false #(a less widely used code layout in ruby)

    or which is the most straightforward way:

      
     i = true
     false 
    

    So, the output is correct. Otherwise, if you were expecting false, then use the boolean and &&.

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