ruby - lazily iterate through an array

foreach, iteration, ruby

Solution

Ruby 2.0 will ship Lazy enumerables (fantastic news!), for now we can warm up the engines using gems like enumerable-lazy:

require 'enumerable/lazy'
xs.lazy.drop(1).each { |x| puts x }

That's not bad, but conceptually it doesn't exactly apply to your case, since you already have an array, not a lazy object (a linked list) that you must traverse to discard elements (ok, we are just discarding one element here, it wouldn't be a deal-breaker). So you could just abstract your solution (that one using a range) as `Enumerable#each_from(start_index)` if you plan to use it a lot.

More: you could also create an extension to enumerable-lazy `Array#lazy_slice(range)`, which would return a `Enumerable#lazy` object. It also looks pretty good: `xs.lazy_slice(1..-1).each { |x| puts x }`

Problem

I want to iterate through a part of an array. For example, I try to print every element except the first one: ``` array[1..-1].each {|e| puts e} ``` But `array[1..-1]` builds a new `Array`. It's wasteful if `array` is very huge. Another straightforward approach: ``` (1...array.size).each { |i| puts array[i] } ``` It works. But I wonder if there are some more elegant tricks.

Original source