Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ||= mean in Ruby? [duplicate]

Tags:

ruby

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

What does ||= mean in Ruby?

like image 797
ben Avatar asked Sep 27 '10 03:09

ben


3 Answers

It's mainly used as a shortform for initializing a variable to a certain value, if it is not yet set.

Think about the statement as returning x || (x = y). If x has a value (other than false), only the left side of the || will be evalutated (since || short-circuts), and x will be not be reassigned. However, if x is false or nil, the right side will be evaluated, which will set x to y, and y will be returned (the result of an assignment statement is the right-hand side).

See http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case for more discussion.

like image 186
Daniel Vandersluis Avatar answered Sep 28 '22 14:09

Daniel Vandersluis


x ||= y is often used instead of x = y if x == nil

like image 36
Nakilon Avatar answered Sep 28 '22 14:09

Nakilon


The idea is the same as with other similar operators (+=, *=, etc):
a ||= b is a = a || b

And this trick is not limited to Ruby only: it goes through many languages with C roots.

edit to repel downvoters.
See one of Jörg's links for more accurate approximation, for example this one.
This is exactly why I don't like Ruby: nothing's ever what it seems.

like image 38
Nikita Rybak Avatar answered Sep 28 '22 14:09

Nikita Rybak