码迷,mamicode.com
首页 > 其他好文 > 详细

ruby hash 默认值的问题

时间:2017-04-01 17:02:19      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:turn   efault   mutate   class   sign   数组   its   out   ruby   

参考: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 默认值的问题

标签:turn   efault   mutate   class   sign   数组   its   out   ruby   

原文地址:http://www.cnblogs.com/lavin/p/6656558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!