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 => [] }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值