Iterating over each element of an array, except the first one

自古美人都是妖i 提交于 2019-12-07 10:52:05

问题


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 { ... }

Edit/clarification: I'd like to avoid allocating a second array. Originally I said I wanted to avoid "copying" the array, which was confusing.


回答1:


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

And now:

arr.each_after(1) do |elem|
  ...
end



回答2:


I want to do this without creating a copy of the array.

1) Internal iterator:

arr = [1, 2, 3]
start_index = 1

(start_index...arr.size).each do |i|
  puts arr[i]
end

--output:--
2
3

2) External iterator:

arr = [1, 2, 3]
e = arr.each
e.next

loop do
  puts e.next
end

--output:--
2
3



回答3:


OK, maybe this is bad form to answer my own question. But I've been racking my brain on this and poring over the Enumerable docs, and I think I've found a good solution:

arr.lazy.drop(1).each { ... }

Here's proof that it works :-)

>> [1,2,3].lazy.drop(1).each { |e| puts e }
2
3

Concise: yes. Idiomatic Ruby… maybe? What do you think?



来源:https://stackoverflow.com/questions/29425064/iterating-over-each-element-of-an-array-except-the-first-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!