在Ruby中,如何设置嵌套散列的默认值? [英] In Ruby, how to set a default value for a nested hash?

查看:172
本文介绍了在Ruby中,如何设置嵌套散列的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我找到了一种在Ruby中正确创建和使用嵌套散列的方法。我立即找到了Paul Morie的解决方案,他回答了他自己的问题:

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



我很快就使用了这个功能,很高兴报告它的工作原理。但是,正如标题所说,我希望次要,内部哈希默认为返回0



我知道你可以在其构造函数中定义散列的默认返回值( Hash.new(0))或者使用 .default hash.default(0))。

但是,你会如何在散列内部使用散列来实现这一点?解析方案

显然我只需要做:

>

hash = Hash.new {| h,k | h [k] = Hash.new(0)}



哎呀。我会尽量不要急于在下次提问。


I recently looked for a way to correctly create and use nested hashes in Ruby. I promptly found a solution by Paul Morie, who answered his own question: hash = Hash.new { |h,k| h[k] = {} }

I promptly went to use this and am glad to report it works. However, as the title says, I'd like the "secondary", "inside" hashes to return 0 by default.

I'm aware that you can define the default return value of a hash both in its constructor ("Hash.new(0)") or using .default ("hash.default(0)").

But how would you do this with hashes inside a hash?

解决方案

Apparently I only had to do:

hash = Hash.new { |h,k| h[k] = Hash.new(0) }

Whoops. I'll try not to be so hasty to ask a question next time.

这篇关于在Ruby中,如何设置嵌套散列的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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