From: Chris Shea Date: 2008-04-05T05:15:08+09:00 Subject: Re: The ||= assignment operator On Apr 4, 1:30 pm, Paul Mucur wrote: > On 4 Apr 2008, at 20:11, Belorion wrote: > > > It was my understanding that the ||= assignment operator assigned > > the value > > on the right-hand side if and only if the left hand side did not > > already > > have a value: > > It's probably better to think of x ||= "ruby" as being short hand for > x = x || "ruby" (which it effectively is) instead of "assign if not > already having a value". If you do this, then you can see why your > last example behaves like it does. > > Don't forget that there are other similar operators like +=, -= and > &&= and they all follow the same pattern: > > x ?= y > x = x ? y > > Where ? is one of -, +, && or ||. > > Hope that this helps. 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"} -- Chris