我怎么能初始化Ruby的哈希里的数组 [英] How can I initialize an Array inside a Hash in Ruby

查看:132
本文介绍了我怎么能初始化Ruby的哈希里的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图初始化数组的哈希值,如

  @my_hash = Hash.new(Array.new)

让我可以:

  @my_hash [你好。推(在街上)
= GT; [在街上]
@my_hash [你好。推(在家)
= GT; [在街上,家]
@my_hash [你好]
= GT;在街上,家]

问题是,任何新的哈希键也返回 [在街上,家]

  @my_hash [再见]
= GT; [在街上,家]
@my_hash [XXX]
= GT; [在街上,家]

!!! ???

我是什么做错了什么是初始化数组的散列的正确方法是什么?


解决方案

  @my_hash = Hash.new(Array.new)

这将创建只有一个数组对象,这是返回的每一个关键是没有找到时间。因为你永远只变异数组,不要再创建一个新的,所有的按键映射到相同的阵列。

您想要做的是:

  @my_hash = Hash.new {| H,K | H [k]的= Array.new}

或只是

  @my_hash = Hash.new {| H,K | H [k]的= []}

传递一个块 Hash.new 从简单的传递参数​​在两个方面有所不同


  1. 该块每执行一个关键是没有找到时间。因此,你会每次都得到一个新的数组。在带参数的版本,这样的说法是一次(之前的叫法),以及这一结果返回每次。


  2. 这样做 H [K] = 你实际上将钥匙插入哈希值。如果你不这样做只是在访问 @my_hash [some_key] 实际上不会引起 some_key 插入在哈希值。


I am trying to initialize a Hash of Arrays such as

@my_hash = Hash.new(Array.new)

so that I can:

@my_hash["hello"].push("in the street")
=> ["in the street"]
@my_hash["hello"].push("at home")
=> ["in the street", "at home"]
@my_hash["hello"]
=>["in the street", "at home"]

The problem is that any new hash key also return ["in the street", "at home"]

@my_hash["bye"]
=> ["in the street", "at home"]
@my_hash["xxx"]
=> ["in the street", "at home"]

!!!???

What am I doing wrong what would be the correct way to initialize a Hash of Arrays?

解决方案

@my_hash = Hash.new(Array.new)

This creates exactly one array object, which is returned every time a key is not found. Since you only ever mutate that array and never create a new one, all your keys map to the same array.

What you want to do is:

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

or simply

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

Passing a block to Hash.new differs from simply passing an argument in 2 ways:

  1. The block is executed every time a key is not found. Thus you'll get a new array each time. In the version with an argument, that argument is evaluated once (before new is called) and the result of that is returned every time.

  2. By doing h[k] = you actually insert the key into the hash. If you don't do this just accessing @my_hash[some_key] won't actually cause some_key to be inserted in the hash.

这篇关于我怎么能初始化Ruby的哈希里的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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