Ruby - 每个起始偏移量 [英] Ruby - each starting offset
问题描述
如何为 ruby 中的 each
循环设置起始偏移量?我希望循环从 a[3]
而不是 a[0]
开始.我该如何设置?
How do I set a starting offset for each
loop in ruby?
I want the loop to begin from a[3]
instead of a[0]
. How do I set that?
a = [ab, cd, ef, gh, hi, jk]
a.each do |i|
#some stuff
end
推荐答案
另一种可能更直接和可读的可能性是使用 Array#drop
:
Another, possibly more direct and readable possibility is to use Array#drop
:
a.drop(3).each do |i|
# do something with item i
end
现在,如果与从 Enumerable
继承的其他方法结合使用,这真的很出色,所以很有可能更好的替代命令式 each
循环.假设您要过滤提取的切片并在之后对其进行转换:
Now this really shines if combined with other methods inherited from Enumerable
, so chances are there's a better alternative to your imperative each
loop. Say you want to filter the extracted slice and transform it afterwards:
a = [0,1,2,3,4,5,6,7]
a.drop(3).select(&:even?).map { |x| x * 2 }
# => [8, 12]
或者说你想打印所有值的列表:
Or say you want to print a list of all the values:
a = ["1", "2", "3", "4", "5"]
puts a.drop(3).join("\n")
输出:
4
5
继承自函数式编程的这些特性使 Ruby 变得如此强大:)
These features inherited from functional programming are what makes Ruby so strong :)
这篇关于Ruby - 每个起始偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!