Ruby && = edge case

A bit of edge, but any idea why && = will behave this way? I am using 1.9.2.

obj = Object.new
obj.instance_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 expected:

obj = Object.new
obj.instance_eval {@foo ||= @foo}
obj.instance_variables # => [:@foo], where @foo is set to nil

Thank!

+5
source share
1 answer

This is because it @barevaluates to false, and therefore &&=will evaluate the expression no further ... Unlike your second expression, which in any case assigns @bar, regardless of whether the following expression resolves. The same applies to a case ||=that evaluates a complete expression, regardless of which initial value is @fooallowed.

, , (undefined) @bar, . &&= x = x && y. x = x && y if x.

+5

All Articles