What does the following code mean in Ruby?
||=
Does it have any meaning or reason for the syntax?
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.
If a class defines a method named + , for example, then that changes the meaning of abbreviated assignment with += for all instances of that class.
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 || .
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.
a ||= b
is a conditional assignment operator. It means:
a
is undefined or falsey, then evaluate b
and set a
to the result.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:
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