From: Eleanor McHugh Date: 2009-05-06T09:45:01+09:00 Subject: Re: '=||' On 6 May 2009, at 00:09, 7stud -- wrote: > Eleanor McHugh wrote: >> Are you referring to ||= ? If so it's one of the augmented assignment >> operators so you won't find it documented separately as it's >> syntactic >> sugar for: >> >> x = x || some_other_value > > Nope. > > h = Hash.new(10) > > h["red"] = h["red"] || 20 > > --output:-- > {"red"=>10} > > > h = Hash.new(10) > h["blue"] ||= 20 > p h > > --output:-- > {} > > > The statement: > > x ||= val > > is actually equivalent to: > > 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. Ellie Eleanor McHugh Games With Brains http://slides.games-with-brains.net ---- raise ArgumentError unless @reality.responds_to? :reason