From: Peter Zotov Date: 2012-04-21T21:39:35+09:00 Subject: Re: What does '||=' mean? Ian M. Asaff писал 21.04.2012 05:20: > 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 The info on that link is incorrect or outdated. On recent Rubies like 1.9.3 the nil guard explicitly does not show a warning if the variable did not exist beforehand. Check it yourself: $ ruby -W2 -e '@ivar ||= 1' $ ruby -W2 -e '@ivar = @ivar || 1' -e:1: warning: instance variable @ivar not initialized > > 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/. >> >> -- WBR, Peter Zotov.