3

What's the best way (in terms of both idiom and efficiency) to find the index of the first non-nil value in an array?

I've come up with first_non_null_index = array.index(array.dup.compact[0])...but is there a better way?

2 Answers 2

6

Ruby 1.9 has the find_index method:

ruby-1.9.1-p378 > [nil, nil, false, 5, 10, 20].find_index { |x| not x.nil? } # detect false values
 => 2 
ruby-1.9.1-p378 > [nil, nil, false, 5, 10, 20].find_index { |x| x }
 => 3 

find_index seems to be available in backports if needed in Ruby earlier than 1.8.7.

Sign up to request clarification or add additional context in comments.

3 Comments

this will wring if array =[nil, nil, nil, nil, nil]
index is an alias of find_index, so [nil, nil,1].index{|x| x } works too.
I find [nil, nil, 5, 10].index(&:present?) in Rails is succinct as long as you aren't concerned about false values.
0

I think the best answer is in the question only. Only change

first_non_null_index = (array.compact.empty?) "No 'Non null' value exist" :  array.index(array.dup.compact[0]

Consider following example

array = [nil, nil, nil,  nil,  nil]
first_non_null_index = array.index(array.dup.compact[0]) #this will return '0' which is wrong

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.