Ruby &&= edge case
Bit of an edge case, but any idea why &&= would behave this way? I'm using 1.9.2.
obj = Object.new
obj.instance_开发者_C百科eval {@bar &&= @bar} # => nil, expected
obj.instance_variables # => [], so obj has no @bar instance variable
obj.instance_eval {@bar = @bar && @bar} # ostensibly the same as @bar &&= @bar
obj.instance_variables # => [:@bar] # why would this version initialize @bar?
For comparison, ||= initializes the instance variable to nil, as I'd expect:
obj = Object.new
obj.instance_eval {@foo ||= @foo}
obj.instance_variables # => [:@foo], where @foo is set to nil
Thanks!
This is, because @bar
evaluates to false, and thus the &&=
would evaluate the expression no further... In contrast to your second expression, which assigns to @bar
in any case, no matter what the following expression resolves to. The same goes with the ||=
case which evaluates the complete expression, no matter what initial value @foo
resolved to.
So the difference between your first two expressions is, that in the first the assignment is dependent on the (undefined) value of @bar
while in the second case you do an unconditional assignment. &&=
is NOT a shortcut for x = x && y
. It is a shortcut for x = x && y if x
.
精彩评论