不能使用数组作为Ruby Hash的默认值? [英] Can't use an array as default values for Ruby Hash?

查看:107
本文介绍了不能使用数组作为Ruby Hash的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将项目添加到散列键。我期待得到这样的结构:

I was adding items to a Hash key. I was expecting to get a structure like this:

{ 
  'a' : [1],
  'b' : [2, 3, 4]
}

以初始化哈希。

irb> hash = Hash.new([])
 => {} 

然后开始使用它:

Then started using it:

irb> hash['a'] << 1
 => [1] 
irb> hash['b'] << 2
 => [1, 2] 

但事实证明:

But it turns out:

irb> hash
 => {}


推荐答案

请改为:

hash = Hash.new{|h, k| h[k] = []}
hash['a'] << 1 # => [1]
hash['b'] << 2 # => [2]

您得到意想不到的结果的原因是您指定了一个空数组作为默认值,但是使用相同的数组;没有复制完成。正确的方法是用一个新的空数组初始化值,就像我的代码一样。

The reason you got your unexpected results is that you specified an empty array as default value, but the same array is used; no copy is done. The right way is to initialize the value with a new empty array, as in my code.

这篇关于不能使用数组作为Ruby Hash的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆