我有一个数组A,想要检查它是否包含重复的值。我该怎么做?
调用uniq
函数(它返回一个没有重复元素的新数组), 然后判断uniq
后的数组是否比原始数组元素少:
if a.uniq.length == a.length
puts "a does not contain duplicates"
else
puts "a does contain duplicates"
end
请注意,数组中的对象需要适当地响应hash
和eql?
才能使uniq
正常工作。
uniq!
将返回 nil
并更改 self 以删除重复项。有很多数组方法可用:http://ruby-doc.org/core/classes/Array.html - Davideql?
没有有意义的响应,那么"重复"到底是什么意思呢?一旦你定义了eql?
,hash
也应该与之一致。 - Karl Knechtel==
相等吗? - sepp2ka.uniq.length == a.length
而不是简单地使用 a.uniq == a
? - Paul Hoffer为了找到重复的元素,我使用以下方法(使用 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]
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}]
.group_by{|e| e}
is equivalent to .group_by(&:itself)
- Nathan Gouy如果使用超过一次,可能需要对 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