Ruby array subtraction without removing items more than once

后端 未结 4 1075
余生分开走
余生分开走 2020-12-03 16:55

The canonical Array difference example in Ruby is:

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]

What\'s the best way to ge

4条回答
  •  执笔经年
    2020-12-03 17:54

    class Array
      def subtract_once(b)
        h = b.inject({}) {|memo, v|
          memo[v] ||= 0; memo[v] += 1; memo
        }
        reject { |e| h.include?(e) && (h[e] -= 1) >= 0 }
      end
    end
    

    I believe this does what I want. Many thanks to @glebm

提交回复
热议问题