Given a Hash
:
hash = {}
This expression:
hash[:key] ||= :value
Expands to:
hash[:key] || hash[:key] = :value
Ruby's logical operators short circuit, which means that hash[:key] = :value
will only be executed if, and only if, hash[:key]
is either false
or nil
.
If it is anything else, its value alone will be sufficient to determine the result of the logical disjunction, and the rest of the expression will not be evaluated.
This is fundamentally different than:
hash[:key] = hash[:key] || :value
In this case, the []=
method will be called either way, and the only difference is which argument it will receive: :value
if hash[:key]
is either false
or nil
, or the value of hash[:key]
itself otherwise.