Double-Pipe Equals (Ruby)

When assigning one variable to another

Danny Poit
Jul 15, 2019
Yes, it’s a picture of a “double pipe.”

If a = 1 and b = nil, and you set b = a, then the value of b will be 1, because you have assigned b to have the value of a.

If a = 1 and b = 2, and you set b = a, then the value of b will also be 1, because you have assigned b to have the value of a, and this replaced the previous value of b, which was 2.

With the regular assignment operator (=), it doesn’t matter what value a variable previously had; when the variable is assigned a new value, it always takes on that value.

The ||= (Double-Pipe Equals) operator assigns a value to a variable only if the variable currently has a nil value.

If a = 1 and b = nil, and you set b ||= a, then the value of b will be 1, because b previously had a nil value, so it is able to be assigned the value of a using the ||= operator.

If a = 1 and b = 2, and you set b ||= a, then the value of b will remain 2, because b already has a non-nil value, so the ||= operator is not able to assign the value of a to it.

--

--

Danny Poit
Danny Poit

Written by Danny Poit

Danny Poit is a web developer with experience in Ruby on Rails and Node.js and a background in film scoring. Grad of Firehose Project, Colt Steele, and Berklee.

No responses yet