1

If I want a part of an array I can use [] or split:

arr = [1,2,3,4,5]
arr[1..3]
=> [2, 3, 4]

But is there a 'general' version of []? Can I apply it to any Enumerator?

enum = arr.each
enum.xxx_method(1..3) # is equal to arr[1..3].each

Of course you can use arr[1..3] directly. But I'm seeking a general way to handle any enumerator.

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

1 Answers1

3

If you have an enumerator, you can count on Enumerable methods drop and take:

# abstract if necessary as enum_slice(range)
enumerator.drop(2).take(3)

If that enumerator is an array you don't need to traverse it, check the method Array#lazy_slice that I asked to be added to enumerable_lazy in relation with your previous question:

require 'enumerable/lazy'

class Array
  def lazy_slice(range)
    Enumerator.new do |yielder|
      range.each do |index|
        yielder << self[index]
      end
    end.lazy
  end
end

some_big_array = (0..10000).to_a # fake array, it won't generally be a range
p some_big_array.lazy_slice(9995..10000).map { |x| 2*x }.to_a
#=> [19990, 19992, 19994, 19996, 19998, 20000]
Community
  • 1
  • 1
tokland
  • 66,169
  • 13
  • 144
  • 170