Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Pipe Symbols in Ruby Variable Assignment? [duplicate]

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?

like image 959
Daniel Upton Avatar asked Dec 21 '10 14:12

Daniel Upton


People also ask

What do || mean in Ruby?

The || operator returns the Boolean OR of its operands. It returns a true value if either of its operands is a true value. If both operands are false values, then it returns a false value.

What does double pipe mean in Ruby?

The code foo ||= bar is almost equivalent to foo = foo || bar . In Ruby (as in many languages, like JavaScript or Io) boolean operators are "guard" operators. Instead of always returning true or false , they evaluate to the value of the first operand that evaluates to a "truthy" value.


1 Answers

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 
like image 140
Klaus Byskov Pedersen Avatar answered Sep 28 '22 10:09

Klaus Byskov Pedersen