views:

47

answers:

1

What's a smart way of using ActiveSupport or perhaps regular built in Ruby functionality to take two arrays and merge them into a hash where each element in an array matches the element in a parallel array? imagine two arrays:

names = ["Danny", "Johnny"]
ages = ["25", "32"]

The end result should be a hash that looks like:

{"Danny" => "25", "Johnny" => "32"}
+3  A: 

If you're using ruby 1.8.7 or above:

Hash[names.zip ages]

or for 1.8.6:

Hash[*names.zip(ages).flatten]
mckeed
using .flatten will cause problems in the case where either array also contains other arrays. In this specific situation it'll be fine, but important to keep in mind
Gareth
Good point, replace `.flatten` with `.sum` if there is any chance of the arrays having other arrays in them.
mckeed