Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there any Array or Enumerable built-in 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'd like to know if this already exists?

like image 636
Geo Avatar asked Oct 21 '25 09:10

Geo


2 Answers

I don't think there's anything built-in, at least I didn't notice anything previously undetected in the Array or Enumerable docs.

This is pretty terse, though:

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

EDIT: Should have mentioned this is Ruby 1.8.6.

ANOTHER EDIT: forgot triple-dot, which saves a whole character, as well as cleaning up the -1, which I wasn't comfortable with:

(0...ar.size).select { |i| ar[i] > 4 }
like image 55
Mike Woodhouse Avatar answered Oct 23 '25 06:10

Mike Woodhouse


I understand this is only ruby 1.9

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

EDIT: for 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? }
like image 29
johnanthonyboyd Avatar answered Oct 23 '25 06:10

johnanthonyboyd