From: Robert Dober Date: 2008-04-05T21:24:43+09:00 Subject: Re: The ||= assignment operator On Sat, Apr 5, 2008 at 10:25 AM, Peņa, Botp wrote: > From: Joshua Ballanco [mailto:jballanc@gmail.com] > # Not at all. Rather, this is just a subtle misunderstanding of > > # how hash is implemented. Consider the following: > # >> h = Hash.new > # => {} > # >> h[:test] ||= 'testing without default' > # => "testing without default" > # >> h > # => {:test=>"testing without default"} > # >> h = Hash.new('default value') > # => {} > # >> h[:test] ||= 'testing with default' > # => "default value" > # >> h > # => {} > # 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: > # >> h = Hash.new > # => {} > # >> puts 'empty' unless h[:test] > # empty > # => nil > # >> h = Hash.new('default value') > # => {} > # >> puts 'empty' unless h[:test] > # => nil > > my question is simple, > > given, > > > h = Hash.new('default value') > #=> {} > > why is > > h[:test] ||= 'this is alternative' > #=> "default value" > h > #=> {} > > different from > > h[:test] = h[:test] || 'this is alternative' > #=> "default value" > h > #=> {:test=>"default value"} > > ?? > > That is not a nice surprise, imho; and the (syntax) sugar is not sweet :) > > kind regards -botp > > I respectfully disagree, this is very well defined behavior, I partially blame the list which *very* often explained to newbies that @x ||= value assignes value to @x when it was not defined before. It is sad that things are incorrectly explained, that is all. Furthermore things are simple (1) lval ||= rval is lval = lval || rval (2) nil || x = x (3) false || x = x (4) non initialized ivars evaluate to nil once one accepts these basic rules of the language there is no surprise. I like the syntactic sugar but to use a recently used quote "DE GVSTIBVS NON DISPVTANDVM EST" Cheers Robert -- http://ruby-smalltalk.blogspot.com/ --- Whereof one cannot speak, thereof one must be silent. Ludwig Wittgenstein