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

2

4

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?

Chitterlings answered 4/5, 2015 at 18:31 Comment(0)
C
15

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.

Chitterlings answered 4/5, 2015 at 18:33 Comment(0)
C
0

Or hash = Hash.new(Hash.new(0))

Coexecutor answered 6/6 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.