说明:iterator模式包括内部遍历(internal iterator )和外部遍历(external iterator)两种,内部遍历是指对象自己已经存在的遍历方法,比如在array中的each方法,外部遍历是用户自定义的方法,额外定义在对象上。下面介绍两种遍历方法的示范代码
#external iterator
fruits = %w(orange apple mango)
fruits.each do |fruit|
puts fruit
end
#internal iterator
class ExternalIterator
def initialize(array)
@array = array
@index = 0
end
def first
@array[0]
end
def next
value = @array[@index]
@index += 1
value
end
def is_done?
@index == @array.length - 1
end
def current_item
@array[@index]
end
def has_next?
@index < @array.length
end
def previous
value = @array[@index]
@index -= 1
value
end
def has_previous?
@index > 0
end
def rewind
@index = 0
end
end
fruits = %w(orange apple mango)
array_iterator = ExternalIterator.new(fruits)
while array_iterator.has_next?
puts array_iterator.next_item
end
https://medium.com/@dljerome/design-patterns-in-ruby-iterator-beead2c6492