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.
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.
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.
&&
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