Created
October 16, 2011 22:11
-
-
Save gregglind/1291493 to your computer and use it in GitHub Desktop.
new iterators in python and ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from discussion of bring the block to the iterator at | |
# http://mettadore.com/ruby/ruby-blocks-seeking-closure/ | |
## Ruby Version | |
''' | |
class Kids < Array | |
def each_one | |
self.each_with_index do |n, i| | |
yield(n) | |
p "Going now to tuck in #{self[i+1]}" if i < (self.length - 1) | |
p "Everyone all snuggled up!" if i == (self.length - 1) | |
end | |
end | |
end | |
kids = Kids.new | |
%w(Wendy Michael John).each{|n| kids << n} | |
kids.each_one do |n| | |
p "Tucking in #{n}" | |
end | |
''' | |
## python version, seems nearly as readable | |
## both seem to shift all the work onto 'make a new kind of iterator' | |
class Kids(list): | |
def each_one(self): | |
L = len(self) | |
for (i,k) in enumerate(self): | |
yield k | |
if i < (L-1): | |
print "Going now to tuck in %r" % (self[i+1]) | |
else: | |
print "Everyone all snuggled up!" | |
kids = Kids("Wendy Michael John".split()) | |
for k in kids.each_one(): | |
print "Tucking in %s" % k |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment