ruby hash 默认值的问题

时间:2023-03-09 19:20:04
ruby  hash 默认值的问题

参考:http://*.com/questions/16159370/ruby-hash-default-value-behavior

使用ruby hash 默认值为空数组,向key 对应的value 追加值然后去get一个不存在的key 时候发现value为 一个非空的arry,不是默认值[]

具体使用示例如下:

 One default Array with mutation

 hsh = Hash.new([])

 hsh[:one] << 'one'
hsh[:two] << 'two' hsh[:nonexistent]
# => ['one', 'two']
# Because we mutated the default value, nonexistent keys return the changed value hsh
# => {}
# But we never mutated the hash itself, therefore it is still empty!
One default Array without mutation hsh = Hash.new([]) hsh[:one] += ['one']
hsh[:two] += ['two']
# This is syntactic sugar for hsh[:two] = hsh[:two] + ['two'] hsh[:nonexistant]
# => []
# We didn't mutate the default value, it is still an empty array hsh
# => { :one => ['one'], :two => ['two'] }
# This time, we *did* mutate the hash.
A new, different Array every time with mutation hsh = Hash.new { [] }
# This time, instead of a default *value*, we use a default *block* hsh[:one] << 'one'
hsh[:two] << 'two' hsh[:nonexistent]
# => []
# We *did* mutate the default value, but it was a fresh one every time. hsh
# => {}
# But we never mutated the hash itself, therefore it is still empty! 47 hsh = Hash.new {|hsh, key| hsh[key] = [] }
# This time, instead of a default *value*, we use a default *block*
# And the block not only *returns* the default value, it also *assigns* it hsh[:one] << 'one'
hsh[:two] << 'two' hsh[:nonexistent]
# => []
# We *did* mutate the default value, but it was a fresh one every time. hsh
# => { :one => ['one'], :two => ['two'], :nonexistent => [] }