是否有内置方法可以从另一个数组中删除 ruby 数组中的元素

问题描述 投票:0回答:1

现在还很早,我觉得我忘记了一些明显的事情,但是有没有一种方法可以从另一个数组中减去一个数组并返回一个删除了确切匹配数量的数组。

# subtract operator
%i[a b a b a c] - %i[a c] # => [:b, :b]

# what I'm looking for
%i[a b a b a c] - %i[a c] # => [:a, :a, :b, :a]

缺少内置方法,这是我的实现。有没有更有效的方法?

def remove lhs, rhs
  ret = []
  rem = rhs
  lhs.each do |val|
    idx = rem.index(val)
    if idx
      rem = rem[0...idx].concat(rem[idx+1..])
    else
      ret << val
    end
  end
  ret
end
remove(%i[a b a b a c], %i[a c]) # => [:b, :a, :b, :a]

ruby
1个回答
0
投票

你可以这样做:

def sub_each lh, rh
    catalog=rh.tally
    lh.select{|sym| 
        if catalog[sym] && catalog[sym]>0 then 
            catalog[sym]-=1
            nil
        else    
            sym
        end
    }
end

p sub_each(%i[a b a b a c], %i[a c])
[:b, :a, :b, :a]
© www.soinside.com 2019 - 2024. All rights reserved.