遍历数组的每个元素(第一个元素除外) [英] Iterating over each element of an array, except the first one
本文介绍了遍历数组的每个元素(第一个元素除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby编写此代码的惯用方式是什么?
What is the idiomatic Ruby way to write this code?
给出一个数组,我想遍历该数组的每个元素,但是跳过第一个.我想这样做而不分配新数组.
Given an array, I would like to iterate through each element of that array, but skip the first one. I want to do this without allocating a new array.
这是我想出的两种方法,但都不是特别优雅.
Here are two ways I've come up with, but neither feels particularly elegant.
这可行,但似乎太冗长了:
This works but seems way too verbose:
arr.each_with_index do |elem, i|
next if i.zero? # skip the first
...
end
这有效,但是分配了一个新数组:
This works but allocates a new array:
arr[1..-1].each { ... }
编辑/说明:我想避免分配第二个数组.最初,我说过我想避免复制"该数组,这很令人困惑.
推荐答案
使用内部枚举器肯定更直观,并且您可以像这样相当优雅地完成此操作:
Using the internal enumerator is certainly more intuitive, and you can do this fairly elegantly like so:
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
这篇关于遍历数组的每个元素(第一个元素除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文