foo = { bar: false }
foo[:bar] ||= true
I expected that to function like foo[:bar] = true unless foo.key? :bar
but it does not. Is there a shorter way to conditionally declare a hash value if it has not already been declared?
You can use .fetch
if you don't need to store the value
hash.fetch(:key, :default)
Or give Hash a proc.
hash = Hash.new { |hash, key| hash[key] = 'default-value' }
hash[:a] = 'foo'
p hash[:b]
# => 'default-value'
Why does ||= on a hash reassign a false value?
Because that's what it's there for: assign if false, otherwise leave alone. What else should it do?
The reason why your code doesn't work has been discussed, e.g. here.
Depending on your use case, setting a default value to the hash may be the most appropriate solution:
foo = {}
foo.default = true