在满足条件之前采取行动

Lui*_*igi 1 ruby arrays

我觉得这应该很容易,我只是碰壁了.

我需要遍历一个数组,直到满足条件.例如:

count = 0    
array = ["","","test","demo"]
Run Code Online (Sandbox Code Playgroud)

我想循环遍历此数组递增计数1,直到找到第一个非空值.所以我想要索引值"test",但是当"test"达到时我想停止循环.

另外,作为旁注,我怎样才能找到数组中第一个非空值的索引?我想知道这两种方法,因为它们都有潜在的应用.

tes*_*ssi 6

你可以两个:)

这会找到第一个非空字符串的索引:

array = ["","","test","demo"]
array.index {|str| !str.empty?}
#=> 2
Run Code Online (Sandbox Code Playgroud)

{|str| !str.empty?}如果您愿意,可以更新-block中的计数,因为Array#index从头到尾通过数组循环.

仅供参考:该index方法是别名find_index