mar*_*ion 1 ruby arrays iterator enumerator
假设我有一个集合@lines,我想迭代它,但我想根据集合的内容来操纵它是如何迭代的,我该怎么做?
即是这样的:
@lines.each_with_index do |line, index|
if (index % 3 = 0)
jump_to index == next_multiple_of_3
end
end
Run Code Online (Sandbox Code Playgroud)
所以看起来像是这样的:
Element | Index
a | 1
b | 2
c | 3
f | 6
g | 7
h | 8
i | 9
l | 12
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
编辑1
请注意,正如我在下面的评论中所解释的那样,我不一定总是希望跳转到特定的倍数.基本上,我想跳转到一些任意索引,该索引由当前迭代中发生的事情决定.
所以第一次走动,它可以跳过3指数上涨,但是下一次跳跃7指数上涨,然后在接下来的5次1跳跃2指数正常,然后指数上涨.
唯一的常数是确定它在原始迭代中如何进展的方式是基于当前迭代块内发生的事情.
使用while循环并自己管理索引.我们不鼓励人们这么做多年.但这是一个合适的案例.:)
idx = 0
while idx < @lines.length
line = @lines[idx]
idx += condition ? x : y # or whatever logic you have
end
Run Code Online (Sandbox Code Playgroud)
当然,这假设@lines能够随机访问.如果不是,请将其设为数组.
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |