Ruby编写代码的惯用方式是什么?
给定一个数组,我想遍历该数组的每个元素,但是跳过第一个。我想这样做而不分配新数组。
这是我想出的两种方法,但都感觉不太优雅。
这可行,但看起来太冗长:
arr.each_with_index do |elem, i|
next if i.zero? # skip the first
...
end
这可行,但分配一个新数组:
arr[1..-1].each { ... }
编辑/说明:我想避免分配第二个数组。最初,我说过我想避免“复制”该阵列,这很令人困惑。
使用内部枚举器当然更加直观,您可以像这样相当优雅地完成此操作:
class Array
def each_after(n)
each_with_index do |elem, i|
yield elem if i >= n
end
end
end
现在:
arr.each_after(1) do |elem|
...
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句