从ruby中的数组中删除重复项

时间:2012-03-07 11:03:22

标签: ruby-on-rails arrays ruby hashmap

我想输出一个散列数组,name对所有散列都是唯一的。我将如何使用ruby进行此操作?

这是我的意见:

input = [{:name => "Kutty", :score => 2, :some_key => 'value', ...},
         {:name => "Kutty", :score => 4, :some_key => 'value', ...},
         {:name => "Baba", :score => 5, :some_key => 'value', ...}]

我希望输出看起来像这样:

  output = [{:name => "Kutty", :score => 4, :some_key => 'value', ...},
            {:name => "Baba", :score => 5, :some_key => 'value', ...}]

4 个答案:

答案 0 :(得分:15)

要根据:名称删除重复项,只需尝试;

output = input.uniq { |x| x[:name] }

演示here

编辑:由于您在评论中添加了排序要求,如果您正在使用Rails,以下是如何选择每个名称得分最高的条目,我看到您已经得到了答案“标准”Ruby以上;

output = input.group_by { |x| x[:name] }
              .map {|x,y|y.max_by {|x|x[:score]}}

可能会有一点解释;第一行groups按名称输入条目,以便每个名称都有自己的条目数组。第二行遍历组,按名称命名,每个名称组maps到分数最高的条目。

演示here

答案 1 :(得分:3)

input = [{:name => "Kutty", :score => 2, :some_key => 'value'},{:name => "Kutty", :score => 4, :some_key => 'value'},{:name => "Baba", :score => 5, :some_key => 'value'}]
p input.uniq { |e| e[:name] }

以上解决方案适用于ruby> 1.9,对于旧版本的ruby,您可以使用以下内容:

input = [{:name => "Kutty", :score => 2, :some_key => 'value'},{:name => "Kutty", :score => 4, :some_key => 'value'},{:name => "Baba", :score => 5, :some_key => 'value'}]
unames = []
new_input = input.delete_if { |e|
  if unames.include?(e[:name])
    true
  else
    unames << e[:name]
    false
  end
}
p new_input

答案 2 :(得分:3)

尝试此解决方案..

input = [{:name => "Kutty", :score => 2, :some_key => 'value'},
         {:name => "Kutty", :score => 4, :some_key => 'value'},
         {:name => "Baba", :score => 5, :some_key => 'value'}]


a = []
output = []
input.collect do |i|
  input.delete(i) if !a.include?(i[:name])
  output << i if !a.include?(i[:name])
  a << i[:name] if !a.include?(i[:name])
end


output = [{:some_key=>"value", :name=>"Kutty", :score=>2}, 
          {:some_key=>"value", :name=>"Baba", :score=>5}] 

<强>已更新

output = {}
input.each do |e|
  ref = output[e[:name]]
  if ref && ref[:score] > e[:score]
    #nothing
  else
    output[e[:name]] = e
  end
end

检查输出:

puts output.values

答案 3 :(得分:1)

input.uniq{|hash| hash[:name]}