From: Jonathan Paisley Date: 2004-12-08T02:42:31+09:00 Subject: Re: Idiom for creating hash from two arrays On Tue, 07 Dec 2004 15:08:50 +0100, Robert Klemme wrote: > "Jonathan Paisley" >> h = Hash[*keys.zip(values).flatten] >> #=> {"three"=>3, "two"=>2, "one"=>1} >> >> Can anyone suggest a better way of doing this? I'm slightly put off by >> the many steps involved in my present solution. > > Here are some others - but IMHO your solution is much nicer: >>> h={} > => {} >>> keys.each_with_index {|e,i| h[e]=values[i]} > => ["one", "two", "three"] >>> h={} > => {} >>> keys.inject(values) do |v,k| > ?> h[k]=v.shift >>> v >>> end Of these (including my original), I think the each_with_index solution is the most transparent and readable, but I don't like having to separately initialize h beforehand. I think I'll stick with what I've got for now, or perhaps implement: def Hash.from_pairs(keys,values) # or some better name h = {} keys.zip(values) do |k,v| h[k] = v end h end (using zip with a block has just occured to me) I did some benchmark tests of all four implementations (my original, your two, and the above). The last is about twice as fast as each_with_index and inject, and at least an order of magnitude faster than my original method involving flattening. Many thanks for your input! Most appreciated.