Ruby difference in array including duplicates

后端 未结 3 960
你的背包
你的背包 2020-12-10 19:55

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

3条回答
  •  天涯浪人
    2020-12-10 20:31

    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.

    By way of example:

    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 gave us the method Enumerable#tally, allowing us to replace the first line of the method with

    h = other.tally
    

提交回复
热议问题