tags:

views:

55

answers:

1
+3  Q: 

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_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!

+5  A: 

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.

hurikhan77
Thanks for clarifying!Also, just got to the part of Programming Ruby 1.9 that explains this... probably should have look it up :/
Alan O'Donnell
@Alan feel free to accept my response as answer if it solves your question.
hurikhan77
Thanks again :) Still figuring out the site...
Alan O'Donnell