Skip to content

Instantly share code, notes, and snippets.

@JulesWang
Created September 27, 2011 12:01
Show Gist options
  • Save JulesWang/1244895 to your computer and use it in GitHub Desktop.
Save JulesWang/1244895 to your computer and use it in GitHub Desktop.
Iterator and Template Method
class List
include Enumerable
def each
yield 1
yield 2
end
#...
end
a = List.new
# e is a iterator here.
p e = a.to_enum
p e.next
p e.next
# When the position reached at the end, StopIteration is raised.
# p e.next
# All the following methods are “Visitors” defined in Enumerable Module
p a.partition {|it| it>1}
p a.collect {|it| it+1}
# ...
class List
include Enumerable
def each
yield 1
yield 2
end
#...
end
a = List.new
# e is a iterator here.
p e = a.to_enum
p e.next
p e.next
# When the position reached at the end, StopIteration is raised.
# p e.next
# All the following methods are template methods defined in Enumerable Module
p a.partition {|it| it>1}
p a.collect {|it| it+1}
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment