From: Adam Prescott Date: 2011-09-10T02:13:03+09:00 Subject: Re: Creating a hash from two arrays On Fri, Sep 9, 2011 at 5:51 PM, simon harrison wrote: > Hi. Can anyone help with this? I'd like to end with a hash like so: > > hash = {{"A" => 'alpha'}, {'B' => 'bravo'}} etc... > > I'm not sure whether I can use group_by and how to handle case > insensitity. Cheers for any help. > > irb(main):001:0> s = ('A'..'Z').to_a > => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", > "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] > > irb(main):003:0> t = %w(alpha bravo Charlie Zebra) > => ["alpha", "bravo", "Charlie", "Zebra"] > First, {{"A" => "alpha"}, {"B" => "bravo"}} isn't valid syntax. You probably meant: {"A" => "alpha", "B" => "bravo", ...} ? You can indeed use group_by: >> (("A".."C").to_a + ("a".."c").to_a).group_by { |e| e[0, 1].downcase } => {"a"=>["A", "a"], "b"=>["B", "b"], "c"=>["C", "c"]} Alternatively, if you want to simply map from a[i] to b[i] in a hash, you can use #zip, #flatten and a splat, in combination with Hash.[]: >> a = %w[a b c d e]; b = (1..5) >> c = a.zip(b) => [["a", 1], ["b", 2], ["c", 3], ["d", 4], ["e", 5]] >> c.flatten! => ["a", 1, "b", 2, "c", 3, "d", 4, "e", 5] >> Hash[*c] # equivalent to Hash["a", 1, "b", 2, ...] => {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5} Or, in one go: >> Hash[*a.zip(b).flatten] => {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5} Zip, flatten, splat. This obviously won't let you store multiple elements ("a" => ["a", "A"]) as in the above approach.