From: Robert Klemme Date: 2004-12-07T23:12:32+09:00 Subject: Re: Idiom for creating hash from two arrays "Jonathan Paisley" schrieb im Newsbeitrag news:pan.2004.12.07.13.40.03.395907@dcs.gla.ac.uk... > Hello all, > > I'm currently using the following code for creating a hash from two arrays, > where one array contains keys and the other the corresponding values: > > keys = ['one','two','three'] > values = [1,2,3] > > 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: >> keys = ['one','two','three'] => ["one", "two", "three"] >> values = [1,2,3] => [1, 2, 3] >> h={} => {} >> keys.each_with_index {|e,i| h[e]=values[i]} => ["one", "two", "three"] >> h => {"three"=>3, "two"=>2, "one"=>1} >> keys = ['one','two','three'] => ["one", "two", "three"] >> values = [1,2,3] => [1, 2, 3] >> h={} => {} >> keys.inject(values) do |v,k| ?> h[k]=v.shift >> v >> end => [] >> h => {"three"=>3, "two"=>2, "one"=>1} >> Kind regards robert