您好我想创建一个散列,如果该名称存在于其他散列中,则该散列将附加名称的电子邮件。我相信会有一小段代码可以完成红宝石的魔力。
Input
a = [
{"email"=>"foobar@gmail.com", "name"=>"Adam"},
{"email"=>"test@gmail.com", "name"=>"John"},
{"email"=>"hello@gmail.com", "name"=>"Adam"}
]
Output
a = [
{"email"=>"foobar@gmail.com", "name"=>"Adam | foobar@gmail.com"},
{"email"=>"test@gmail.com", "name"=>"John"},
{"email"=>"hello@gmail.com", "name"=>"Adam | hello@gmail.com "}
]
答案 0 :(得分:1)
这是另一种选择:
# get names
names = a.map {|e| e['name'] }
# find duplicates
duplicates = names.detect {|e| names.count(e) > 1 }
# append email to duplicates
a.each { |e| e['name'] = "#{e['name']} | #{e['email']}" if duplicate.include?(e['name'])}
答案 1 :(得分:0)
鉴于您的输入
a = [
{"email"=>"foobar@gmail.com", "name"=>"Adam"},
{"email"=>"test@gmail.com", "name"=>"John"},
{"email"=>"hello@gmail.com", "name"=>"Adam"}
]
我将提供一个巧妙命名的我自己的比较哈希
b = [
{"name"=>"Adam"},
{"name"=>"Adam"}
]
这是你的红宝石魔法
a.map do |hash_a|
# This is the 'magic' line that compares the values of
# the two hashes name values
if b.any? { |hash_b| hash_b['name'] == hash_a['name'] }
hash_a['name'] << " | #{hash_a['email']}"
hash_a
else
hash_a
end
end
输出:
[
{
"email" => "foobar@gmail.com",
"name" => "Adam | foobar@gmail.com"
},
{
"email" => "test@gmail.com",
"name" => "John"
},
{
"email" => "hello@gmail.com",
"name" => "Adam | hello@gmail.com"
}
]