Ruby search in offset array

I am looking for a way to do the following in Ruby in a cleaner way:

class Array
  def find_index_with_offset(offset, &block)
    [offset..-1].find &block
  end
end

offset = array.find_index {|element| element.meets_some_criterion?}
the_object_I_want = 
    array.find_index_with_offset(offset+1) {|element| element.meets_another_criterion?}

So, I look for a Ruby array for the index of an object, and then do a subsequent search to find the first object that matches another criterion and has a higher index in the array. Is there a better way to do this?

What I mean by pure: something that is not related to explicitly slicing an array. When you do this several times, the calculation of the cutting indices becomes messy. I would like to continue working with the original array. This is easier to understand and less error prone.

NB. In my actual code, I don't have a monkey processed array, but I want to pay attention to the fact that I expect that I will duplicate the existing Array / Enumerable functionality


Changes

  • offset + 1 ;
  • "" .
+1
1

. , , . , - :

module Enumerable
  def find_multi *procs
    return nil if procs.empty?
    find do |e|
      if procs.first.call(e)
        procs.shift
        next true if procs.empty?
      end
      false
    end
  end
end


a = (1..10).to_a
p a.find_multi(lambda{|e| e % 5 == 0}, lambda{|e| e % 3 == 0}, lambda{|e| e % 4 == 0})
#=> 8

: , - :

array.drop_while{|element|
  !element.meets_some_criterion?
}.drop(1).find{|element|
  element.meets_another_criterion?
}
+2

Source: https://habr.com/ru/post/1617980/


All Articles