我觉得这应该很容易,我只是碰壁了。
我需要遍历数组直到满足条件。例如:
count = 0
array = ["","","test","demo"]
我想遍历这个数组,递增计数 1,直到找到第一个非空值。所以我想要 "test"
的索引值,但是当达到 "test"
时我想停止循环。
另外,作为旁注,我怎样才能找到数组中第一个非空值的索引?我想知道这两种方法,因为它们都有潜在的应用。
最佳答案
你可以同时拥有 :)
这会找到第一个非空字符串的索引:
array = ["","","test","demo"]
array.index {|str| !str.empty?}
#=> 2
您可以在 {|str| 中更新计数!str.empty?}
-block 如果你喜欢,因为 Array#index
从头到尾循环遍历数组。
仅供引用:index
方法是 find_index
的别名
关于ruby - 执行操作直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20097922/