创建一个哈希值作为数组和默认值作为空数组 [英] Creating a Hash with values as arrays and default value as empty array

查看:49
本文介绍了创建一个哈希值作为数组和默认值作为空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Ruby 中创建一个具有默认值作为空数组的哈希

I want to create a Hash in Ruby with default values as an empty array

所以,我编码

x = Hash.new([])

但是,当我尝试将一个值推入其中时

However, when I try to push a value into it

x[0].push(99)

所有键都被 99 推入该数组.我该如何解决?

All the keys get 99 pushed into that array. How do I resolve this?

推荐答案

Lakshmi 是对的.当您使用 Hash.new([]) 创建哈希时,您创建了一个数组对象.

Lakshmi is right. When you created the Hash using Hash.new([]), you created one array object.

因此,对于每个 Hash 中缺失的键,都会返回相同 数组.

Hence, the same array is returned for every missing key in the Hash.

这就是为什么,如果编辑共享数组,更改会反映在所有丢失的键上.

That is why, if the shared array is edited, the change is reflected across all the missing keys.

使用:

Hash.new { |h, k| h[k] = [] }

为散列中每个缺失的键创建并分配一个数组,使其成为唯一的对象.

Creates and assigns a new array for each missing key in the Hash, so that it is a unique object.

这篇关于创建一个哈希值作为数组和默认值作为空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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