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?
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 }
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? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With