Geo
Geo

Reputation: 96827

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?

Upvotes: 4

Views: 4693

Answers (5)

Grandpa
Grandpa

Reputation: 3233

No, but you can always monkey patch 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]                                                        

Upvotes: 1

Erlock
Erlock

Reputation: 1968

Just let explode the power of inject 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)

Upvotes: 1

johnanthonyboyd
johnanthonyboyd

Reputation: 31

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? }

Upvotes: 3

EmFi
EmFi

Reputation: 23450

It's essentially Mike Woodhouse's answer reformatted to remove the ugly range.

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

Here's a version of johnanthonyboyd's answer that works with Ruby 1.8.7

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

Upvotes: 0

Mike Woodhouse
Mike Woodhouse

Reputation: 52316

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 }

Upvotes: 7

Related Questions