Wednesday, August 27, 2014

Iterator pattern ruby

Iterator is too obvious in ruby, so assume some theoretical example.
class Iterator
  def first; end
  def last; end
  def next; end
  def current; end
  def has_next?; end
end

class InfiniteNumbers < Iterator
  def initialize
    @current = 0
  end
  
  def first
    1
  end
  
  def last
    raise "Infinite number"
  end
  
  def next
    @current += 1
  end
  
  def current
    @current
  end
  
  def has_next?
    true
  end  
end

iterator = InfiniteNumbers.new
puts 100.times.collect { iterator.next }.join(',')

No comments:

Post a Comment