Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to reject Ruby array elements by their index

Tags:

arrays

ruby

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?

like image 511
das-g Avatar asked May 26 '15 12:05

das-g


People also ask

How do you reject in Ruby?

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.

How do you return an index of an element in an array in Ruby?

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.


1 Answers

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 }
like image 87
fylooi Avatar answered Nov 14 '22 21:11

fylooi