From: Robert Klemme Date: 2004-06-25T01:53:07+09:00 Subject: Re: N Dimensional Hash? "Jim Freeze" schrieb im Newsbeitrag news:20040624134324.GA33615@freeze.org... > Hi > > I'm looking for an object that behaves like a > n-dimensional hash. We'll start with two dimensions > to make this easy. > > Lets say I have the data table > > [ > %w{mini cooper red}, > %w{ford focus white}, > %w{ford mustang blue}, > %w{ab cd 1}, > %w{abc d 2}, > %w{a bcd 3}, > ] > > Obviously I could build hash with: > > h = { "mini" => {}, > "ford" => {}, > "ab" => {}, > "abc" => {}, > "a" => {} > } > > h["mini"] = { "cooper" => "red" } > h["ford"] = { "focus" => "white", "mustang" => "blue" } > h["ab"] = { "cd" => 1 } > h["abc"] = { "d" => 2 } > h["a"] = { "bcd" => 3 } > > But this is painful. > Before I go and write a class to do this, is there > something that already does this. Like, maybe tuples, > which I don't understand. > > ..Hmm, I would describe this as a hierarchal struct with > named arguments. > > h[:make=>"mini", :model=>"cooper"] #=> "red" > sames as: > h[:model=>"cooper", :make=>"mini"] #=> "red" The typical idiom is: ins = lambda {|h,k| h[k] = Hash.new &ins} h = Hash.new &ins like in >> ins = lambda {|h,k| h[k] = Hash.new &ins} => # >> h=Hash.new &ins => {} >> h["foo"] => {} >> h["foo"]["bar"] => {} >> h => {"foo"=>{"bar"=>{}}} >> h["bar"]["test"] = "val" => "val" >> h => {"foo"=>{"bar"=>{}}, "bar"=>{"test"=>"val"}} Alternatively you can use Arrays as hash keys. But that depends on your requirements. Kind regards robert