From: 7stud -- Date: 2009-05-06T10:38:24+09:00 Subject: Re: '=||' Eleanor McHugh wrote: > On 6 May 2009, at 00:09, 7stud -- wrote: >> h = Hash.new(10) >> >> x = val unless x > It seems you've misunderstood what happens under the hood when using > augmented assignment with tables as '||=' then becomes syntactic sugar > for 'x[] = x[] || some_other_value' and the assignment is performed > via '[]=' rather than '='. '[]=' will not create a key if it believes > it already exists and this is the cause of the behaviour you're seeing. > > h = Hash.new(10) > p h["blue"] => 10 > h["blue"] ||= 20 > p h => {} > > In this case when '||=' invokes the assignment it finds that h["blue"] > already contains a value because of the default so the hash method > '[]=' doesn't attempt to create a new key because it appears that the > key already exists. > > Contrast this to: > > h = Hash.new(10) > p h["blue"] => 10 > h["blue"] = nil > p h => { "blue" => nil } > h["blue"] ||= 10 > p h => { "blue" => 10 } > h["blue"] ||= 20 > p h => { "blue" => 10 } > > Here the key has been explicitly set equal to nil and '||=' acts the > way we'd expect an augmented assignment to work with scalar types. > > Finally if no default is set for the table: > > h = {} > h["red"] ||= 10 > p h => {"red" => 10} > > The key is always created as expected. > Why do I need to care about what's going on under the hood? If two things produce different results, then how can one be considered syntactic sugar for the other. In my opinion, "syntactic sugar" means that the two formats can be used interchangeably--with experienced programmers naturally gravitating to the shorter, easier to type format, and inexperienced programmers preferring the longer, but easier to understand format. -- Posted via http://www.ruby-forum.com/.