Double Pipe Symbols in Ruby Variable Assignment?

Daniel Upton picture Daniel Upton · Dec 21, 2010 · Viewed 28.2k times · Source

Possible Duplicate:
What does ||= mean in Ruby?

Forgive me if this is a newby question but im reading a book on rails where the writer used this expression in a helper method:

@current_user ||= User.find_by_id(session[:user_id])

Is this use of double pipes still a Boolean OR statement?

If so how does it work?

Answer

Klaus Byskov Pedersen picture Klaus Byskov Pedersen · Dec 21, 2010

It's a conditional assignment. From here:

 x = find_something() #=>nil
 x ||= "default"      #=>"default" : value of x will be replaced with "default", but only if x is nil or false
 x ||= "other"        #=>"default" : value of x is not replaced if it already is other than nil or false