I have a nested dictionary/hash structure in Ruby like this:
d = {
:foo => {
:hoo => nil,
:baz => {
# ...
},
},
:bar => {
:doo => {
# ...
},
:loo => nil,
},
# ...
}
Every individual dictionary is of unknown size. Its keys are symbols and its values are either nil
or another dictionary. I am trying to write two methods:
down()
takes the current dictionary and a valid key as arguments and returns a pointer to that value (either nil or another dictionary).up()
takes the current dictionary and returns a pointer to the outer dictionary it is contained within.
down()
is straightforward (it is the same as d[:foo]
), but I am hesitant to just use d[:foo]
because up()
is basically impossible without storing some additional structural/navigation information about d
as down()
is called.
The return values cannot be a copy of anything in d
, they must be pointers. I am still confused about which situations are pass-by-value vs pass-by-ref in Ruby, but I do know all of its "effectively a pointer" variables are mutable.
Update:
When I say "takes the current dictionary" I am just referring to some variable dict
such that dict = d
or dict = (some child of d)
. dict
is either a dictionary or nil. For example:
d = # ...
dict = down(d, :foo)
# dict is now the current dictionary and points to {:hoo=>nil,:baz=>{}} in d
dict2 = down(dict, :baz)
# down() "takes the current dictionary" (dict)
# then returns a new current dictionary (dict2)
In my attempts at a solution, it has seemed essential that some additional entity is keeping track of the level at which the current dictionary resides.