如何检查数组是否有重复项?

时间:2010-12-04 01:25:34

标签: ruby arrays

我有一个数组A.我想检查它是否包含重复值。我该怎么做?

4 个答案:

答案 0 :(得分:123)

只需在其上调用uniq(返回一个没有重复的新数组),看看uniq ed数组的元素是否少于原始数组:

if a.uniq.length == a.length
  puts "a does not contain duplicates"
else
  puts "a does contain duplicates"
end

请注意,数组中的对象需要响应hasheql?,才能使uniq正常工作。

答案 1 :(得分:34)

为了找到重复的元素,我使用这种方法(使用Ruby 1.9.3):

array = [1, 2, 1, 3, 5, 4, 5, 5]
=> [1, 2, 1, 3, 5, 4, 5, 5]
dup = array.select{|element| array.count(element) > 1 }
=> [1, 1, 5, 5, 5]
dup.uniq
=> [1, 5]

答案 2 :(得分:10)

如果要返回重复项,可以执行以下操作:

dups = [1,1,1,2,2,3].group_by{|e| e}.keep_if{|_, e| e.length > 1}
# => {1=>[1, 1, 1], 2=>[2, 2]}

如果您只想要值:

dups.keys
# => [1, 2]

如果您想要重复数量:

dups.map{|k, v| {k => v.length}}
# => [{1=>3}, {2=>2}]

答案 3 :(得分:4)

如果多次使用它,可能想要monkeypatch Array:

class Array
  def uniq?
    self.length == self.uniq.length
  end
end

然后:

irb(main):018:0> [1,2].uniq?
=> true
irb(main):019:0> [2,2].uniq?
=> false