开发者

Why am I seeing different results for two expressions in Ruby, one uses '&&', other uses 'and' operator? [duplicate]

This question already has answers here: 开发者_C百科 Difference between "and" and && in Ruby? (8 answers) Closed 7 years ago.

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜