In Ruby, how to set a default value for a nested hash?

女生的网名这么多〃 提交于 2019-12-24 03:25:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30037397/in-ruby-how-to-set-a-default-value-for-a-nested-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!