2010-06-05 72 views

回答

6

Ruby 1.9的有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_index看來,如果需要的紅寶石比1.8.7早在backports可用。

+0

如果數組= [零,零,零,零,零] – Salil 2010-06-05 04:12:33

+0

指數是find_index的別名,這將擰乾,使[零,零, 1]的.index {| X | x}也起作用。 – steenslag 2010-06-05 20:30:35

+0

我發現[nil,nil,5,10] .index(&:present?)在Rails中是簡潔的,只要您不關心錯誤的值。 – TJChambers 2015-04-30 21:22:08

0

我認爲最好的答案是在問題中。 僅更改

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

考慮以下示例

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