From: David Heitzman Date: 2012-04-22T03:22:56+09:00 Subject: Re: What does '||=' mean? Oh wow, a subtle distinction, but important. I did not know. if the left hand side is non-nil then no assignment happens at all. Thanks, David On 04/21/2012 10:44 AM, Florian Gilcher wrote: > Close. > > a ||= b > > Is actually equivalent to > > a || a = b > > This is not as obvious in the ivar case, but combined with [] access > like hashes, it is a bit different: > > foo[:bar] || foo[:bar] = 'batz' > > [] is called once if :bar is present, and []= is called once if :bar is > not present. > > While in: > > foo[:bar] = foo[:bar] || 'batz' > > both [] and []= are called, independent of the value if :bar. > > > On Apr 21, 2012, at 3:20 AM, Ian M. Asaff wrote: > >> equivalent to >> >> @ivar = @ivar || value >> >> ruby || short circuits, so if @ivar is nil, then value gets assigned >> to @ivar. it's referred to as a "nil guard". >> >> see http://forums.pragprog.com/forums/130/topics/3644 >> >> On Fri, Apr 20, 2012 at 9:15 PM, Soichi Ishida > > wrote: >> >> Well, as stated in the subject, what does '||=' mean? >> >> It's from >> >> def current_cart >> if session[:cart_id] >> @current_cart ||= Cart.find(session[:cart_id]) #HERE!!! >> session[:cart_id] = nil if @current_cart.purchased_at >> end >> if session[:cart_id].nil? >> @current_cart = Cart.create! >> session[:cart_id] = @current_cart.id >> end >> @current_cart >> end >> >> Is this Rails issue? I thought it's some Ruby grammar thing, because I >> know there is an expression, '|='. >> >> Thanks in advance. >> >> >> soichi >> >> -- >> Posted via http://www.ruby-forum.com/. >> >> > > -- > Florian Gilcher > > smtp: flo@andersground.net > jabber: Skade@jabber.ccc.de > gpg: 533148E2 >