ruby

How to iterate over all but first element of an enumerable


I run the following code:

> a = [1,2,3].collect
 => #<Enumerator: [1, 2, 3]:collect> 
> b = a.next
 => 1 
> a.each do |x| puts x end
1
2
3
=> [nil, nil, nil] 

I would expect the result of the do to be 2, 3 since I've already read the first element of a. How I achieve a result of 2, 3 elegantly?

Edit:

To clarify, I don't want to skip the first entry, I just want to process it differently. So I want both b and the loop.


Solution

  • How about this?

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

    Here's how you can continue walking the iterator

    a = [1,2,3]
    
    b = a.each # => #<Enumerator: [1, 2, 3]:each>
    b.next # skip first one
    
    loop do
      c = b.next
      puts c
    end
    # >> 2
    # >> 3