数组中的Ruby差异包括重复项 [英] Ruby difference in array including duplicates

查看:28
本文介绍了数组中的Ruby差异包括重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

[1,2,3,3] - [1,2,3] produces the empty array []. Is it possible to retain duplicates so it returns [3]?

推荐答案

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

I am so glad you asked. I would like to see such a method added to the class Array in some future version of Ruby, as I have found many uses for it:

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

此处提供了该方法的描述及其一些应用程序的链接.

A description of the method and links to some of its applications are given 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,允许我们用

Ruby v2.7 gave us the method Enumerable#tally, allowing us to replace the first line of the method with

h = other.tally

这篇关于数组中的Ruby差异包括重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆