ruby hash 默认值的问题
Posted lavin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby hash 默认值的问题相关的知识,希望对你有一定的参考价值。
参考:http://stackoverflow.com/questions/16159370/ruby-hash-default-value-behavior
使用ruby hash 默认值为空数组,向key 对应的value 追加值然后去get一个不存在的key 时候发现value为 一个非空的arry,不是默认值[]
具体使用示例如下:
1 One default Array with mutation 2 3 hsh = Hash.new([]) 4 5 hsh[:one] << ‘one‘ 6 hsh[:two] << ‘two‘ 7 8 hsh[:nonexistent] 9 # => [‘one‘, ‘two‘] 10 # Because we mutated the default value, nonexistent keys return the changed value 11 12 hsh 13 # => {} 14 # But we never mutated the hash itself, therefore it is still empty! 15 One default Array without mutation 16 17 hsh = Hash.new([]) 18 19 hsh[:one] += [‘one‘] 20 hsh[:two] += [‘two‘] 21 # This is syntactic sugar for hsh[:two] = hsh[:two] + [‘two‘] 22 23 hsh[:nonexistant] 24 # => [] 25 # We didn‘t mutate the default value, it is still an empty array 26 27 hsh 28 # => { :one => [‘one‘], :two => [‘two‘] } 29 # This time, we *did* mutate the hash. 30 A new, different Array every time with mutation 31 32 hsh = Hash.new { [] } 33 # This time, instead of a default *value*, we use a default *block* 34 35 hsh[:one] << ‘one‘ 36 hsh[:two] << ‘two‘ 37 38 hsh[:nonexistent] 39 # => [] 40 # We *did* mutate the default value, but it was a fresh one every time. 41 42 hsh 43 # => {} 44 # But we never mutated the hash itself, therefore it is still empty! 45 46 47 hsh = Hash.new {|hsh, key| hsh[key] = [] } 48 # This time, instead of a default *value*, we use a default *block* 49 # And the block not only *returns* the default value, it also *assigns* it 50 51 hsh[:one] << ‘one‘ 52 hsh[:two] << ‘two‘ 53 54 hsh[:nonexistent] 55 # => [] 56 # We *did* mutate the default value, but it was a fresh one every time. 57 58 hsh 59 # => { :one => [‘one‘], :two => [‘two‘], :nonexistent => [] }
以上是关于ruby hash 默认值的问题的主要内容,如果未能解决你的问题,请参考以下文章
什么会给我像 ruby readline 这样的默认值?