Logan Capaldo
2/21/2006 5:48:00 PM
On Feb 21, 2006, at 12:33 PM, henon wrote:
> hi,
> i am searching for an implementation of a hierarchic datastructure
> that
> behaves similar to a file system except that get of an inexistent path
> returns nil and set of an unexistent path creates the required nodes
> silently.
>
> example:
> d=HierarchicData.new
>
> d[:foo, :bar] # => nil
> d[:foo, :bar]=42
> d[:foo, :bar] # => 42
>
> d[:foo, :foo, 0, 1, :bar]=Object.new # creates a hash in an array
> in an
> array in a hash in a hash
>
> i want to check if this kind of data structure (or similar) has been
> implemented already as library. if not i am going to do it.
>
> thx for any comments!
> -- henon
>
>
Have you considered this?
class HierarchicData < Hash
def [](*args)
super(args)
end
def []=(*args)
keys = args[0..(args.length - 2)]
value = args.last
super(keys, value)
end
end
irb(main):012:0> d = HierarchicData.new
=> {}
irb(main):013:0> d[:foo, :bar]
=> nil
irb(main):014:0> d[:foo, :bar] = 42
=> 42
irb(main):015:0> d[:foo, :bar]
=> 42
irb(main):016:0> d[:foo, :foo, 0, 1, :bar] = Object.new
=> #<Object:0x315d24>