Ruby difference in array including duplicates

后端 未结 3 961
你的背包
你的背包 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:20

    As far as I know, you can't do this with a built-in operation. Can't see anything in the ruby docs either. Simplest way to do this would be to extend the array class like this:

    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
    

    For all I know there's a more efficient way to do this, also

提交回复
热议问题