Ruby中的哈希成语哈希? [英] Hashes of Hashes Idiom in Ruby?

查看:65
本文介绍了Ruby中的哈希成语哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中创建哈希散列可以方便地进行二维(或更多)二维查找.但是,在插入时必须始终检查哈希中是否已经存在第一个索引.例如:

Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists in the hash. For example:

h = Hash.new
h['x'] = Hash.new if not h.key?('x')
h['x']['y'] = value_to_insert

最好在自动创建新哈希的情况下执行以下操作:

It would be preferable to do the following where the new Hash is created automatically:

h = Hash.new
h['x']['y'] = value_to_insert

类似地,当查找第一个索引不存在的值时,如果返回nil而不是接收针对[[]'错误的未定义方法,则是更可取的.

Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error.

looked_up_value = h['w']['z']

一个人可以创建具有这种行为的Hash包装器类,但是是否存在用于完成此任务的Ruby惯用语?

One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?

推荐答案

您可以传递 Hash.new 的功能是执行一个块,以在查询的值尚不存在时产生默认值:

You can pass the Hash.new function a block that is executed to yield a default value in case the queried value doesn't exist yet:

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

当然,这可以递归完成.有

Of course, this can be done recursively. There's an article explaining the details.

为了完整起见,这是本文中针对任意深度哈希的解决方案:

For the sake of completeness, here's the solution from the article for arbitrary depth hashes:

hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)}))

最初提出此解决方案的人是肯特·西比列夫.

The person to originally come up with this solution is Kent Sibilev.

这篇关于Ruby中的哈希成语哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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