Source

iscsi-tools / lib / iscsi / array_enum.rb

require 'delegate'

module ISCSI
  # An object that behaves like an Enumerator and also like an Array. Construct
  # using an array of seed objects and a factory block that turns seed objects
  # into array contents. 
  # 
  #   a = ArrayEnum.new(%q(a b c)) { |e| e.succ }
  #   a.to_a # => %w(b c d)
  #
  class ArrayEnum < Delegator
    def initialize array, &cons
      # Behaves like an enumerator over array
      super(Enumerator.new do |y| 
        array.each do |el| 
          y << cons.call(el)
        end
      end)
    end
  
    def __getobj__
      @delegate
    end
    def __setobj__ obj
      @delegate = obj
    end
  
    def [] *args
      to_a[*args]
    end
    def to_a
      @a ||= super
    end
  end
end