3

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.

2 Answers 2

13

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]
Sign up to request clarification or add additional context in comments.

1 Comment

.map(&:last) would be a good replacement for .map { |pair| pair[1] } if you wanted to cut down the noise a bit.
7

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.