Explain this ruby idiom: a ||= b

Technology CommunityCategory: RubyExplain this ruby idiom: a ||= b
VietMX Staff asked 3 years ago

Is it a common idiom that strong ruby developers will use all the time.

# a = b when a == false
# otherwise a remains unchanged
a || a = b # (Kudos to Markus Prinz)
a = 1
b = 2
a ||= b #=> a = 1
a = nil
b = 2
a ||= b #=> a = 2
a = false
b = 2
a ||= b #=> a = 2