Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'||=' operator in Ruby

Tags:

ruby

Could some one explain to me the meaning of the following Ruby code? (I saw this code snippet in one guy's project):

car ||= (method_1 || method_2 || method_3 || method_4)

What is the difference between the above code and the following code?

car = method_1 || method_2 || method_3 || method_4

----------update--------------

Ok, I got the meaning of ||= operator after read @Dave's explanation, my next question is if both method_2, method_3 and method_4 return a value, which one's value will be assigned to car? (I suppose car is nil initially)

like image 815
Leem.fin Avatar asked Dec 14 '11 14:12

Leem.fin


2 Answers

It's an assignment operator for 'Conditional Assignment'

See here -> http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators

Conditional assignment:

 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

Operator ||= is a shorthand form of the expression:

x = x || "default" 

EDIT:

After seeing OP's edit, the example is just an extension of this, meaning:

car = method_1 || method_2 || method_3 || method_4

Will assign the first non-nil or non-false return value of method_1, method_2, method_3, method_4 (in that order) to car or it'll retain its old value.

like image 60
Dave Avatar answered Oct 13 '22 08:10

Dave


car ||= (method_1 || method_2) 

is equivalent to

car = (car || (method_1 || method_2)) 

In general,

x op= y 

means

x = x op y
like image 29
Armen Tsirunyan Avatar answered Oct 13 '22 09:10

Armen Tsirunyan