From: Yossef Mendelssohn Date: 2008-04-05T16:07:02+09:00 Subject: Re: The ||= assignment operator On Apr 5, 12:46 am, Joshua Ballanco wrote: > Peņa, Botp wrote: > > From: Chris Shea [mailto:cms...@gmail.com] > > # It's better to think of x ||= "ruby" as x || x = "ruby". > > # > > # -- > > # h = Hash.new('default value') > > # > > # h[:test] ||= 'assigned value' > > # h # => {} > > # > > # # same as: > > # h[:test] || h[:test] = 'assigned value' > > # h # => {} > > # > > # # not: > > # h[:test] = h[:test] || 'assigned value' > > # h # => {:test=>"default value"} > > > i'd say that's a bug in design (unless x+=1 is now x+x=1 ;) > > > kind regards -botp > > Not at all. Rather, this is just a subtle misunderstanding of how hash > is implemented. > The only reason that Chris' example behaves like "x || x = stuff" is > because he's defined a default value for the hash. If you set a default > value, than you'll never have a keyed value be empty (i.e. nil). > Consider further: > I think the confusion is that, in Chris' example, there's no assignment, > so the hash only holds the default value temporarily (i.e. just long > enough to not evaluate to nil or false). > -- > Posted viahttp://www.ruby-forum.com/. There was a long thread about this some time ago, and I'm too tired to search for it now. In the end, it came down a difference of opinion. Some people say this violates their expectations because they're told that `var op= value` translates to `var = var op value` always. Other people say this is expected because `var ||= value` really means `var = value unless var` and everybody should know that. Personally, I am in the former camp. I think of the latter as an optimization that works in many places, but optimizations are usually a form of cheating and cheaters eventually get caught. In Ruby, this cheater gets caught in the web of deceit centered around hashes with default values. Note that `hash_with_default_value[key] ||= val` is the only place where this is even an issue. -- -yossef