sep*_*p2k 127
只需调用uniq它(它返回一个没有重复的新数组)并查看uniqed数组是否具有比原始数组少的元素:
if a.uniq.length == a.length
puts "a does not contain duplicates"
else
puts "a does contain duplicates"
end
Run Code Online (Sandbox Code Playgroud)
请注意,数组中的对象需要响应hash并且eql?有意义uniq才能正常工作.
jmo*_*iro 35
为了找到重复的元素,我使用这种方法(使用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]
Run Code Online (Sandbox Code Playgroud)
Ben*_*ier 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]}
Run Code Online (Sandbox Code Playgroud)
如果你只想要值:
dups.keys
# => [1, 2]
Run Code Online (Sandbox Code Playgroud)
如果你想要重复的数量:
dups.map{|k, v| {k => v.length}}
# => [{1=>3}, {2=>2}]
Run Code Online (Sandbox Code Playgroud)
如果不止一次使用它,可能想要monkeypatch Array:
class Array
def uniq?
self.length == self.uniq.length
end
end
Run Code Online (Sandbox Code Playgroud)
然后:
irb(main):018:0> [1,2].uniq?
=> true
irb(main):019:0> [2,2].uniq?
=> false
Run Code Online (Sandbox Code Playgroud)