foo = { bar: false }
foo[:bar] ||= true
我预计功能像foo[:bar] = true unless foo.key? :bar
但它没有。如果尚未声明散列值,是否有更简短的方式来声明散列值?为什么|| =在哈希重新分配一个错误的值?
foo = { bar: false }
foo[:bar] ||= true
我预计功能像foo[:bar] = true unless foo.key? :bar
但它没有。如果尚未声明散列值,是否有更简短的方式来声明散列值?为什么|| =在哈希重新分配一个错误的值?
您可以使用.fetch
如果你不需要存储价值
hash.fetch(:key, :default)
或者给哈希PROC。
hash = Hash.new { |hash, key| hash[key] = 'default-value' }
hash[:a] = 'foo'
p hash[:b]
# => 'default-value'
为什么|| =一个散列重新分配一个假值?
因为这就是它的作用:如果为false,否则保持不变。它还应该做什么?