From: Sandor Szuecs Date: 2010-10-24T18:27:42+09:00 Subject: Re: Convert Array to nested Hash On Oct 24, 2010, at 7:25 AM, Zhi-Qiang Lei wrote: > Dear All, > > I'm seeking a method to convert an array like: > > [ > ["A", "a", 1] > ["A", "b", 2] > ["B", "a", 1] > > ] > > into a hash as follow: > { > {"A" => {"a" => 1, "b" => 2}}, > {"B" => {"a" => 1}} > } > > Do you have any idea on this? Thanks in advance. I don't think that you really want to add 3 layers of dictionary. If you really want this, then you think about your abstractions to get a simpler solution. a = [ ["A", "a", 1], ["A", "b", 2], ["B", "a", 1] ] def a_to_h(a) h={} a.map do |nested| key = nested.shift h[key] ||= {} h[key].merge!({ nested.shift => nested.shift }) end h end irb:0> a_to_h(a) => {"A"=>{"a"=>1, "b"=>2}, "B"=>{"a"=>1}} All the best, Sandor Szücs --