A common sight in Ruby code is ||=:

What’s that you say?

||= is used for conditional assignment:

a = nil
a ||= 25 # Set a since it was nil
a ||= 24 # Don't set a since it is 25

One caveat is that the implementation of ||= is conditional on whether a is eithernil or false, so

a = nil
a ||= false # set to false
a ||= true # set to true

If it helps to think of it this way, the closest easy approximation would be a || a = 24.


Another far less used, but pretty cool one is &&=, as you can imagine, its the reverse. It will assign only if there is a non-nil, non-false value present:

a = 24
a &&= nil # a becomes nil
a &&= 25 # a stays as nil