Chris Clouten
Chris Clouten

Reputation: 1075

How to combine two arrays of hashes?

I am querying an API to get information on users given their email address. For example:

emails = [{'email' => '[email protected]'}, {'email' => '[email protected]'}, ... ]

The query hash I pass to the API has to be in this format. The API returns an array of hashes on the information it found for each user. If there was no information it returns an empty hash in that index. The results are returned in the same order as they are queried, i.e. the first index of the response array is the info for [email protected]. A sample response might look like this:

response = [{'gender' => 'male', 'age' => '24 - 35'}, {'gender' => 'male'}, ... ]

How can I combine my array of email hashes with the response array such that I will get something like the following?

combined = [
    {'email' => '[email protected]', 'gender' => 'male', 'age' => '24 - 35'}, 
    {'email' => '[email protected]', 'gender' => 'male'}, ... ]

Upvotes: 3

Views: 150

Answers (3)

toro2k
toro2k

Reputation: 19228

My version using Array#zip:

emails = [{'email' => '[email protected]'}, {'email' => '[email protected]'}]
response = [{'gender' => 'male', 'age' => '24 - 35'}, {'gender' => 'male'}]

combined = emails.zip(response).map { |e, r| e.merge(r) }
# => [{"email"=>"[email protected]", "gender"=>"male", "age"=>"24 - 35"},
#     {"email"=>"[email protected]", "gender"=>"male"}]

Upvotes: 5

Marek Lipka
Marek Lipka

Reputation: 51151

The other way to achieve this, basing on @Arup Rakshit's answer:

emails = [{'email' => '[email protected]'}, {'email' => '[email protected]'} ]
response = [{'gender' => 'male', 'age' => '24 - 35'}, {'gender' => 'male'}]
emails.map.with_index { |hash, i| hash.merge(response[i]) }

Upvotes: 6

Arup Rakshit
Arup Rakshit

Reputation: 118271

How is this?

emails = [{'email' => '[email protected]'}, {'email' => '[email protected]'} ]
response = [{'gender' => 'male', 'age' => '24 - 35'}, {'gender' => 'male'}]
combined = emails.each_index.map { |i| emails[i].merge(response[i]) }

Upvotes: 6

Related Questions