数组中的Ruby差异包括重复

[1,2,3,3] - [1,2,3]产生空数组[] 。 是否可以保留重复项以便返回[3]

你问我很高兴。 我希望在未来的Ruby版本中看到这样的方法添加到类Array中,因为我发现它有很多用途:

 class Array def difference(other) cpy = dup other.each do |e| ndx = cpy.rindex(e) cpy.delete_at(ndx) if ndx end cpy end end 

这里给出了该方法的描述和它的一些应用的链接。

举例来说:

 a = [1,2,3,4,3,2,4,2] b = [2,3,4,4,4] a - b #=> [1] a.difference b #=> [1,2,3,2] 

据我所知,你不能通过内置操作来做到这一点。 在ruby文档中也看不到任何内容。 最简单的方法是扩展数组类,如下所示:

 class Array def difference(array2) final_array = [] self.each do |item| if array2.include?(item) array2.delete_at(array2.find_index(item)) else final_array << item end end end end 

据我所知,还有一种更有效的方法

编辑:正如user2864740在问题评论中所建议的,使用Array#slice! 是一个更优雅的解决方案

 def arr_sub(a,b) a = a.dup #if you want to preserve the original array b.each {|del| a.slice!(a.index(del)) if a.include?(del) } return a end 

信用:

我原来的答案

 def arr_sub(a,b) b = b.each_with_object(Hash.new(0)){ |v,h| h[v] += 1 } a = a.each_with_object([]) do |v, arr| arr << v if b[v] < 1 b[v] -= 1 end end arr_sub([1,2,3,3],[1,2,3]) # a => [3] arr_sub([1,2,3,3,4,4,4],[1,2,3,4,4]) # => [3, 4] arr_sub([4,4,4,5,5,5,5],[4,4,5,5,5,5,6,6]) # => [4]