开发者

index of first non-nil value in array

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 wi开发者_开发知识库th first_non_null_index = array.index(array.dup.compact[0])...but is there a better way?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜