views:

62

answers:

2

print (-1 == -1) and (myobj.nil?)

true

print (-1 == -1) && (myobj.nil?)

false

Note, myobj.nil? returns false so, should not this always be false.

+1  A: 

Because they have different operator precedence.

The first evaluates as:

(print (-1 == -1)) and (myobj.nil?)

It prints true, because -1 == -1, then print returns nil and nil and false is nil.

The second is equivalent to:

print ((-1 == -1) && (myobj.nil?))

It prints (true && false), which is false, then print returns nil.

Matthew Flaschen
but why should that matter in this case, -1==-1 always evaluates to true, and myobj.nil? evaluates to false. so the net result should always be false.
Shekhar
oh ok, so if it was used in conditional expression likeif (-1 == -1) and (myobj.nil?)both, would have same result?
Shekhar
Jörg W Mittag
Jorg, thanks. this is really helpful, as I never realized print was being considered part of the expression.
Shekhar
+3  A: 

&& and and have different precedence. In particular, and has very low precedence, lower than almost anything else.

The return value of print is nil, at least in Ruby 1.8. Therefore, the first expression reduces like this:

(print (-1 == -1)) and myobj.nil?
(print    true)    and myobj.nil? # => with the side-effect of printing "true"
      nil          and myobj.nil?
      nil

While the second expression reduces like this:

print ((-1 == -1) && myobj.nil?)
print (   true    && myobj.nil?)
print                myobj.nil?
print                 false       # => with the side-effect of printing "false"
            nil
Jörg W Mittag