如何组合两个哈希数组?

时间:2014-03-10 16:02:23

标签: ruby arrays hash

我正在查询API以获取有关用户电子邮件地址的用户信息。例如:

emails = [{'email' => 'example1@test.com'}, {'email' => 'example2@test.com'}, ... ]

我传递给API的查询哈希必须采用这种格式。 API为每个用户找到的信息返回一个哈希数组。如果没有信息,则返回该索引中的空哈希。结果以与查询的顺序相同的顺序返回,即响应数组的第一个索引是example1@test.com的信息。示例响应可能如下所示:

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

如何将我的电子邮件哈希数组与响应数组合并,以便获得如下内容?

combined = [
    {'email' => 'example1@test.com', 'gender' => 'male', 'age' => '24 - 35'}, 
    {'email' => 'example2@test.com', 'gender' => 'male'}, ... ]

3 个答案:

答案 0 :(得分:6)

这是怎么回事?

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

答案 1 :(得分:6)

另一种实现这一目标的方法,基于@Arup Rakshit的答案:

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

答案 2 :(得分:5)

我的版本使用Array#zip

emails = [{'email' => 'example1@test.com'}, {'email' => 'example2@test.com'}]
response = [{'gender' => 'male', 'age' => '24 - 35'}, {'gender' => 'male'}]

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