Index of the first non-nil value in an array

What is the best way (in terms of idiom and efficiency) to find the index of the first value other than nil in the array?

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

+3
source share
2 answers

Ruby 1.9 has a method find_index:

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_indexseems to be available in backports if needed in Ruby before 1.8.7.

+6
source

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

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

Consider the 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
0
source

Source: https://habr.com/ru/post/1748629/


All Articles