Monday, April 15, 2013

Getting nth and slice for Enumerator::Lazy

Ruby 2.0's Enumerator::Lazy does not have a method for getting nth or getting slice, because Enumerator::Lazy has no indexers whileEnumerable has ones. But, we can same thing defining method on Enumerator::Lazy class.
class Enumerator::Lazy
  def at(nth)
    self.drop(nth).first
  end
  def slice(lower, upper)
    self.drop(lower).take(upper - lower + 1)
  end
end
irb(main):009:0> oneToFive = [1,2,3,4,5].lazy
=> #<Enumerator::Lazy: [1, 2, 3, 4, 5]>
irb(main):010:0> oneToFive.at 1
=> 2
irb(main):011:0> oneToFive.slice 1, 3
=> #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: [1, 2, 3, 4, 5]>:drop(1)>:take(3)>
irb(main):012:0> (oneToFive.slice 1, 3).to_a
=> [2, 3, 4]

No comments:

Post a Comment