如何在 Ruby on Rails 中删除哈希中的重复项? [英] How to remove duplicates in a hash in Ruby on Rails?
问题描述
我有一个像这样的哈希:
<预><代码>[{:lname =>棕色的",:email =>"james@intuit.com",:fname =>詹姆士"},{:lname =>零,:email =>"布拉德@intuit.com",:fname =>零},{:lname =>史密斯",:email =>"布拉德@intuit.com",:fname =>布拉德"},{:lname =>零,:email =>"布拉德@intuit.com",:fname =>零},{:lname =>史密斯",:email =>"布拉德@intuit.com",:fname =>布拉德"},{:lname =>零,:email =>"布拉德@intuit.com",:fname =>零}]我想学习的是如何删除重复的记录.意思是,看看有几个brad@intuit.com"我怎样才能删除重复的记录,这意味着删除所有其他有brad@intuit.com"电子邮件的人......让电子邮件成为关键而不是另一个字段?
我知道这是一个旧线程,但 Rails 在 'Enumerable' 上有一个名为 'index_by' 的方法,在这种情况下可以很方便:
list = [{:lname =>棕色的",:email =>"james@intuit.com",:fname =>詹姆士"},{:lname =>零,:email =>"布拉德@intuit.com",:fname =>零},{:lname =>史密斯",:email =>"布拉德@intuit.com",:fname =>布拉德"},{:lname =>零,:email =>"布拉德@intuit.com",:fname =>零},{:lname =>史密斯",:email =>"布拉德@intuit.com",:fname =>布拉德"},{:lname =>零,:email =>"布拉德@intuit.com",:fname =>零}]
现在您可以按如下方式获取唯一行:
list.index_by {|r|r[:email]}.values
合并具有相同电子邮件 ID 的行.
list.group_by{|r|r[:email]}.map 做 |k, v|v.inject({}) { |r, h|r.merge(h){ |key, o, n|○ ||} }结尾
自定义但有效的方法:
list.inject({}) do |r, h|(r[h[:email]] ||= {}).merge!(h){ |key, old, new|老||新的 }r终值
I have a hash like so:
[
{
:lname => "Brown",
:email => "james@intuit.com",
:fname => "James"
},
{
:lname => nil,
:email => "brad@intuit.com",
:fname => nil
},
{
:lname => "Smith",
:email => "brad@intuit.com",
:fname => "Brad"
},
{
:lname => nil,
:email => "brad@intuit.com",
:fname => nil
},
{
:lname => "Smith",
:email => "brad@intuit.com",
:fname => "Brad"
},
{
:lname => nil,
:email => "brad@intuit.com",
:fname => nil
}
]
What I would like to learn how to do is how to remove a record if it is duplicate. Meaning, see how there are several "brad@intuit.com" how can I remove the duplicate records, meaning remove all the others that have an email of "brad@intuit.com".... Making email the key not the other fields?
I know this is an old thread, but Rails has a method on 'Enumerable' called 'index_by' which can be handy in this case:
list = [
{
:lname => "Brown",
:email => "james@intuit.com",
:fname => "James"
},
{
:lname => nil,
:email => "brad@intuit.com",
:fname => nil
},
{
:lname => "Smith",
:email => "brad@intuit.com",
:fname => "Brad"
},
{
:lname => nil,
:email => "brad@intuit.com",
:fname => nil
},
{
:lname => "Smith",
:email => "brad@intuit.com",
:fname => "Brad"
},
{
:lname => nil,
:email => "brad@intuit.com",
:fname => nil
}
]
Now you can get the unique rows as follows:
list.index_by {|r| r[:email]}.values
To merge the rows with the same email id.
list.group_by{|r| r[:email]}.map do |k, v|
v.inject({}) { |r, h| r.merge(h){ |key, o, n| o || n } }
end
Custom but efficient method:
list.inject({}) do |r, h|
(r[h[:email]] ||= {}).merge!(h){ |key, old, new| old || new }
r
end.values
这篇关于如何在 Ruby on Rails 中删除哈希中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!