Hash default value not being used [duplicate]

岁酱吖の 提交于 2019-12-24 00:01:09

问题


Today I tried the following snippets of code and I don't understand why I get different results between them. As far as I can understand they are the same.

One uses the default value off Hash and the other snippet creates an empty array for the key before it'll be accessed.

Anyone who understands what's going on? :)

# Hash default if the key doesn't have a value set is an empty Array
a = Hash.new([])
a[:key] << 2 # => [2]
p a # => {} nil
p a[:key] # => [2]
p a.keys # => []
p a.values # => []

# Explicitly add an array for all nodes before creating
b = Hash.new
b[:key] ||= []
b[:key] << 2 # => [2]
p b # => {:key=>[2]}
p b.keys # => [:key]

Ruby version 1.8.7


回答1:


When you did a[:key] << 2, you slipped that empty array default value out and added 2 to it (modifying the actual array, not the reference) without letting the hash object a know that you had changed anything. You modified the object that a was using as a default, so you will see this as well:

p a[:wat] #=> [2]
p a[:anything] #=> [2]

In the second example, you made a new array, and use b[:key]= which tells b that it has a value under that key.

Try this if you want the best of both worlds:

c = Hash.new([])
c[:key] += [2]

This will access c[:key] and make a new array with + and reassign it.




回答2:


Maybe this will help:

a = Hash.new { |hash, key| hash[key] = [] }
a[:key] << 2 # => [2]
a[:key]      # => [2]
p a          # => {:key=>[2]}


来源:https://stackoverflow.com/questions/2692141/hash-default-value-not-being-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!