根据一组索引删除数组的内容

delete_at只接受一个索引。 使用内置方法实现这一目标的好方法是什么? 不必是一个集合,也可以是一个索引数组。

arr = ["a", "b", "c"] set = Set.new [1, 2] arr.delete_at set # => arr = ["a"] 

一内胆:

 arr.delete_if.with_index { |_, index| set.include? index } 

重新打开Array类并为此添加新方法。

 class Array def delete_at_multi(arr) arr = arr.sort.reverse # delete highest indexes first. arr.each do |i| self.delete_at i end self end end arr = ["a", "b", "c"] set = [1, 2] arr.delete_at_multi(set) arr # => ["a"] 

如果您不想重新打开课程,这当然可以作为一个独立的方法编写。 确保索引的顺序相反是非常重要的,否则您将在数组中稍后更改应该删除的元素的位置。

试试这个:

 arr.reject { |item| set.include? arr.index(item) } # => [a] 

我认为这有点难看;)也许有人建议更好的解决方案?

function方法:

 class Array def except_values_at(*indexes) ([-1] + indexes + [self.size]).sort.each_cons(2).flat_map do |idx1, idx2| self[idx1+1...idx2] || [] end end end >> ["a", "b", "c", "d", "e"].except_values_at(1, 3) => ["a", "c", "e"]