Let's say I have an arbitrarily deep nested Hash h
:
h = {
:foo => { :bar => 1 },
:baz => 10,
:quux => { :swozz => {:muux => 1000}, :grimel => 200 }
# ...
}
And let's say I have a class C
defined as:
class C
attr_accessor :dict
end
How do I replace all nested values in h
so that they are now C
instances with the dict
attribute set to that value? For instance, in the above example, I'd expect to have something like:
h = {
:foo => <C @dict={:bar => 1}>,
:baz => 10,
:quux => <C @dict={:swozz => <C @dict={:muux => 1000}>, :grimel => 200}>
# ...
}
where <C @dict = ...>
represents a C
instance with @dict = ...
. (Note that as soon as you reach a value which isn't nested, you stop wrapping it in C
instances.)
If we override
inspect
inC
to give a more friendly output like so:and then run with your example
h
this gives:Also, if you add an
initialize
method toC
for settingdict
:then you can reduce the 3 lines in the middle of
convert_hash
to justh[k] = C.new(convert_hash_h[k])