tags:

views:

40

answers:

2

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?

+4  A: 

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.

Mark Rushakoff
this will wring if array =[nil, nil, nil, nil, nil]
Salil
index is an alias of find_index, so [nil, nil,1].index{|x| x } works too.
steenslag
@steenslag: Strangely, Ruby only has `Array#index`, `Array#find_index`, and `Enumerable#find_index`. There is no `Enumerable#index`. So `index` works fine for arrays (as in the original question), but you can't rely on that for an `Enumerable`.
Mark Rushakoff
A: 

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
Salil