Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ||= (or-equals) mean in Ruby?

Tags:

operators

ruby

What does the following code mean in Ruby?

||= 

Does it have any meaning or reason for the syntax?

like image 957
collimarco Avatar asked Jun 15 '09 11:06

collimarco


People also ask

What does the => operator does in Ruby?

Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.

What does += mean in Ruby?

If a class defines a method named + , for example, then that changes the meaning of abbreviated assignment with += for all instances of that class.

What is the difference between || and or in Ruby?

The: or operator has a lower precedence than || . or has a lower precedence than the = assignment operator. and and or have the same precedence, while && has a higher precedence than || .

What is the name of this operator === in Ruby?

Triple Equals Operator (More Than Equality) Our last operator today is going to be about the triple equals operator ( === ). This one is also a method, and it appears even in places where you wouldn't expect it to. Ruby is calling the === method here on the class.


1 Answers

a ||= b is a conditional assignment operator. It means:

  • if a is undefined or falsey, then evaluate b and set a to the result.
  • Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.

For example:

a ||= nil # => nil a ||= 0 # => 0 a ||= 2 # => 0  foo = false # => false foo ||= true # => true foo ||= false # => true 

Confusingly, it looks similar to other assignment operators (such as +=), but behaves differently.

  • a += b translates to a = a + b
  • a ||= b roughly translates to a || a = b

It is a near-shorthand for a || a = b. The difference is that, when a is undefined, a || a = b would raise NameError, whereas a ||= b sets a to b. This distinction is unimportant if a and b are both local variables, but is significant if either is a getter/setter method of a class.

Further reading:

  • http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html
like image 183
Steve Bennett Avatar answered Sep 29 '22 23:09

Steve Bennett