How can I use an index or rindex with a block in Ruby?

Is there a built-in Array or Enumerable array that allows me to search for an element using a block and return its index?

Something along the lines of:

ar = [15,2,33,4,50,69]
indexes = ar.find_indexes {|item| item > 4 == 0}
# indexes will now contain 0,2,4,5

It would be very easy to add my own, but I would like to know if this already exists?

+3
source share
5 answers

I do not think that there is something built-in, at least I did not notice anything previously not found in Array or Enumerable docs.

This is pretty short:

(0..ar.size-1).select { |i| ar[i] > 4 }

EDIT: Must mention this Ruby 1.8.6.

: , , -1, :

(0...ar.size).select { |i| ar[i] > 4 }
+7

, ruby ​​1.9

indexes = ar.collect.with_index { |elem, index| index if elem > 4 }.
             select { |elem| not elem.nil? }

EDIT: ruby ​​1.8 try

require 'enumerator'
indexes = ar.to_enum(:each_with_index).
             collect { |elem, index| index if elem > 4 }.
             select { |elem| not elem.nil? }
+3

Just explode the power of the injection method !!!; -)

ar.inject([]){|a,i| a.empty? ? a << [0, i] : a << [a.last[0]+1,i]}
  .select{|a| a[1] > 4}
  .map{|a| a[0]}

(works with ruby ​​1.8.6)

+1
source

No, but you can always neutralize it if you want:

class Array
  def find_indexes(&block)
    (0..size-1).select { |i| block.call(self[i]) }
  end
end

ar = [15,2,33,4,50,69]
p ar.find_indexes {|item| item > 4 }  #=> [0, 2, 4, 5]                                                        
+1
source

Essentially, Mike Woodhouse's answer is formatted to remove the ugly range.

ar.each_index.select{|item| item > 4}

Here is the version of johnanthonyboyd answer that works with Ruby 1.8.7

ar.enum_with_index.each.select{|item| item.first > 4}.map(&:last)
0
source

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


All Articles