简体   繁体   English

数组作为红宝石哈希值

[英]array as value in hash in ruby

I want to have a hash whose key is a string and the value is an array. 我想要一个哈希,其键是一个字符串,值是一个数组。 I tried it the following way: 我通过以下方式尝试了它:

h = Hash.new([]) # => {} 
h["one"]         # => [] 
h["two"]         # => [] 
h["one"].push 1  # => [1] 
h["one"]         # => [1] 
h["two"]         # => [1] //why did it assign it to h["two"] also??

What is the correct way to do it? 正确的方法是什么?

You get this behavior because [] that you passed into new method isn't copied but referenced in all unset hash keys. 之所以会出现这种现象,是因为传递给new方法的[]不会被复制,而是在所有未设置的哈希键中引用。 So h['one'] references the same object as h['two'] . 因此, h['one']引用与h['two']相同的对象。 So if you modify object referenced by h['one'] (using push method), h['two'] will also be modified. 因此,如果您修改h['one']引用的对象(使用push方法),则h['two']也将被修改。

The correct way to set default value which will be initialized for every single hash key is to use block: 设置默认值的正确方法是使用块:

h = Hash.new { |hash, key| hash[key] = [] }

I usually do it like this: 我通常这样做:

h = Hash.new { |h,k| h[k] = [] }
h['one']
h
# => { 'one' => [] }
h['two'] << 12
h
# => { 'one' => [], 'two' => [12] }

Which is more verbose and (IMO) reads nicer. 哪个更详细,并且(IMO)读起来更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM