3

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.

Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

2 Answers2

5

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 }

tokland
  • 66,169
  • 13
  • 144
  • 170
1
array.each_with_index {|x, i| puts x unless i.eql?0}
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
kiddorails
  • 12,961
  • 2
  • 32
  • 41