Question

How do I return Enumerator from my array wrapper without using already existing array iterators?

class MyArray

  def initialize
   @inner = []
  end

  def each
    index = 0
    while index < @inner.size
      yield @inner[index] if block_given?
      index += 1
    end
  end
end

I can't figure out how to avoid calling things like @inner.each at the end of the each method.

Était-ce utile?

La solution

Given:

@inner = [1, 2, 3]

Code

@inner.to_enum

will return an enumerator.

enum = @inner.to_enum
enum.each{|e| p e}
# => 1, 2, 3
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top