Given a Ruby array ary1
, I'd like to produce another array ary2
that has the same elements as ary1
, except for those at a given set of ary1
indices.
I can monkey-patch this functionality onto Ruby's Array
class with
class Array
def reject_at(*indices)
copy = Array.new(self)
indices.uniq.sort.reverse_each do |i|
copy.delete_at i
end
return copy
end
end
which I can then use like this:
ary1 = [:a, :b, :c, :d, :e]
ary2 = ary1.reject_at(2, 4)
puts(ary2.to_s) # [:a, :b, :d]
While this works fine, I have the feeling that I must be missing something obvious. Is there some functionality like this already built into Ruby? E.g., can and should Array#slice
be used for this task?