[1,2,3,3] - [1,2,3]
生成空数组 []
。是否可以保留重复项以便返回 [3]
?
最佳答案
很高兴你提出这个问题。我希望在 Ruby 的某些 future 版本中将这样的方法添加到 Array
类中,因为我发现它有很多用途:
class Array
def difference(other)
h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
reject { |e| h[e] > 0 && h[e] -= 1 }
end
end
给出了该方法的描述及其一些应用程序的链接 here .
举个例子:
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 v2.7 为我们提供了方法 Enumerable#tally , 允许我们将方法的第一行替换为
h = other.tally
关于数组中的 Ruby 差异包括重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429659/