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?
Ruby | Enumerable reject() function The reject() of enumerable is an inbuilt method in Ruby returns the items in the enumerable which does not satisfies the given condition in the block. It returns an enumerator if no block is given. Parameters: The function takes a block whose condition is used to find the elements.
Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.
Don't think there is an inbuilt solution for this. Came up with the following:
ary1 = [:a, :b, :c, :d, :e]
indexes_to_reject = [1,2,3]
ary1.reject.each_with_index{|i, ix| indexes_to_reject.include? ix }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With