Given an array [0, 0, 1, 0, 1], is there a built-in method to get all of the indexes of values greater than 0? So, the method should return [2, 4].
find_index only returns the first match.
Working in Ruby 1.9.2.
In Ruby 1.8.7 and 1.9, iterator methods called without a block return an Enumerator object. So you could do something like:
[0, 0, 1, 0, 1].each_with_index.select { |num, index| num > 0 }.map { |pair| pair[1] }
# => [2, 4]
Stepping through:
[0, 0, 1, 0, 1].each_with_index
# => #<Enumerator: [0, 0, 1, 0, 1]:each_with_index>
_.select { |num, index| num > 0 }
# => [[1, 2], [1, 4]]
_.map { |pair| pair[1] }
# => [2, 4]
.map(&:last) would be a good replacement for .map { |pair| pair[1] } if you wanted to cut down the noise a bit.I would do
[0, 0, 1, 0, 1].map.with_index{|x, i| i if x > 0}.compact
And if you want that as a single method, ruby does not have a built in one, but you can do:
class Array
def select_indice &p; map.with_index{|x, i| i if p.call(x)}.compact end
end
and use it as:
[0, 0, 1, 0, 1].select_indice{|x| x > 0}