From: "Peña, Botp" Date: 2008-04-05T17:25:46+09:00 Subject: Re: The ||= assignment operator 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