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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With