Exactly, infinite depth would be nice as it would make a more temporal= ly
portable solution.
With it, you have infinite depth, until in a branch you decide to stop
by appending (<<) a value.
Then you fix the depth of that branch.
The proxy looks to be working great. =A0I am a bit
confused as to why the << method in the proxy doesn't overwrite a leaf with
a new array though. =A0I'm not complaining as it works the way I want =
it
to,
When you access h[1][2][3], a proxy object is inserted in the hash for
that key. The proxy object remembers the hash and the key. When you
call << on the proxy object, it replaces itself in the hash with an
empty array, to which it appends the value. So further calls to
h[1][2][3] will return that array and no proxy objects anymore. It
works the same for the upper levels: calling h[1] inserts a proxy in
the hash. When you call [] on it (for example h[1][2]) it replaces
h[1] with a hash.
Maybe this clarifies a bit more:
/temp$ cat nested_hash_array.rb && ruby nested_hash_array.rb
class ProxyDefault
=A0 =A0 =A0 =A0def initialize hash, key
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0@hash =3D hash
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0@key =3D key
=A0 =A0 =A0 =A0end
=A0 =A0 =A0 =A0def [](key)
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 puts "the hash is: #{@hash.inspect} when= calling [] on the
proxy object"
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 @hash[@key] =3D Hash.new {|hash,key| Pro= xyDefault.new(hash,
key)}
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 puts "the hash is: #{@hash.inspect} afte= r replacing the
proxy with a hash"
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0@hash[@key][key]
=A0 =A0 =A0 =A0end
=A0 =A0 =A0 =A0def << value
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0puts "the hash is: #{@hash.inspect} when = calling << on the
proxy object"
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0@hash[@key] =3D [value]
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0puts "the hash is: #{@hash.inspect} after= replacing the
proxy with an array"
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0@hash[@key]
=A0 =A0 =A0 =A0 end
end
h =3D Hash.new {|hash,value| ProxyDefault.new(hash, value)}
h[1][2] << "value"
p h
p h[1][2]
the hash is: {} when calling [] on the proxy object
the hash is: {1=3D>{}} after replacing the proxy with a hash
the hash is: {} when calling << on the proxy object
the hash is: {2=3D>["value"]} after replacing the proxy with an array
{1=3D>{2=3D>["value"]}}
["value"]
Jesus.