"henon" <meinrad.recheis / gmail.com> schrieb im Newsbeitrag news:1140543137.277936.273070 / o13g2000cwo.googlegroups.com... > 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! There is the usual idiom of nested hashes: insert = lambda {|h,k| h[k] = Hash.new(&insert)} tree = Hash.new(&insert) Then you can do >> tree[:foo][:bar] => {} >> tree[:foo][:bar]=42 => 42 >> tree => {:foo=>{:bar=>42}} Of course you can wrap that in a single class: class HT def initialize insert = lambda {|h,k| h[k] = Hash.new(&insert)} @tree = Hash.new(&insert) end def [](*a) a.inject(@tree) {|h,k| h[k]} end def []=(*a) val = a.pop key = a.pop a.inject(@tree) {|h,k| h[k]}[key]=val val end end >> h[:foo, :bar] => {} >> h => #<HT:0x101dc690 @tree={:foo=>{:bar=>{}}}> >> h[:foo, :bar]=24 => 24 >> h => #<HT:0x101dc690 @tree={:foo=>{:bar=>24}}> >> h[:bar]=2345 => 2345 >> h => #<HT:0x101dc690 @tree={:bar=>2345, :foo=>{:bar=>24}}> HTH robert