From: dblack@... Date: 2007-01-13T08:55:26+09:00 Subject: Re: What does this mean? ||= HI -- On Sat, 13 Jan 2007, Chris Gernon wrote: > Justin Ko wrote: >> I'm looking at this method and don't understand what ||= means: > > Much like 'x += 1' is a shortcut for 'x = x + 1', 'x ||= 1' is a > shortcut for 'x = x || 1'. > > The significance of this is that the || method doesn't simply return a > boolean value; it checks the first argument, returns it if it evaluates > to 'true' (i.e. is something other than false or nil), and otherwise > returns the second argument. So it's commonly used as a shortcut for an > if/then statement, checking if the first argument is nil (or false). So > the following are all equivalent: > > if @account > @account > else > Account.find(session[:account_id]) > end > > is the same as: > > @account = @account || Account.find(session[:account_id]) > > is the same as: > > @account ||= Account.find(session[:account_id]) Your first example doesn't set @account; it just tests it. You'd need to do the assignment explicitly: @account = if @account @account else Account.find(session[:account_id] end David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)