Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby &&= edge case

Tags:

ruby

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!

like image 248
Alan O'Donnell Avatar asked Jun 06 '10 02:06

Alan O'Donnell


People also ask

What does Ruby symbolize?

Rubies are often associated with wealth and prosperity. Many ancient crowns were decorated with rubies, because they represented good fortune and courage. The ruby's deep red color also has ties to love, passion, and raw emotion.

What does Ruby mean spiritually?

Ruby is believed to promote loving, nurturing, health, knowledge and wealth. It has been associated with improved energy and concentration, creativity, loyalty, honor and compassion. Ruby is thought to be protective of home, possessions and family.

Are rubies rare?

Rubies are one of the rarest gemstones. The rarest rubies come from Burma (Myanmar), due to their high quality and exceptional color. Good quality rubies larger than one carat are also extremely rare—and expensive.

Is Ruby hard to learn?

It's a model-view-controller framework that provides default database, web page, and web service structures. And no, it's not hard to learn at all! Between its thriving community and its straightforward workflow, Ruby on Rails may be one of, if not THE, most beginner-friendly frameworks in existence.


1 Answers

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.

like image 196
hurikhan77 Avatar answered Sep 20 '22 02:09

hurikhan77