Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 976
Matt Brictson Avatar asked Mar 16 '23 13:03

Matt Brictson


2 Answers

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
like image 130
PinnyM Avatar answered Mar 19 '23 01:03

PinnyM


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
like image 32
7stud Avatar answered Mar 19 '23 02:03

7stud