Double-Pipe Equals (Ruby)

When assigning one variable to another

Image for post
Image for post
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 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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store