2
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?

Drew
  • 15,158
  • 17
  • 68
  • 77

3 Answers3

3

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'
Ven
  • 19,015
  • 2
  • 41
  • 61
1

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?

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

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
Community
  • 1
  • 1
user2398029
  • 6,699
  • 8
  • 48
  • 80