From: dagbrown@... (Dave Brown) Date: 2004-04-07T14:39:20+09:00 Subject: Re: deciding between ruby and python In article , gabriele renzi wrote: : In ruby you're forced to build a huge array any time you use zip, whle : in python you can delay the creation of the yielded pair till they're : actually useful. Nope. irb(main):001:0> a=[1,2,3,4,5] => [1, 2, 3, 4, 5] irb(main):002:0> b=[6,7,8,9,10] => [6, 7, 8, 9, 10] irb(main):003:0> a.zip(b) => [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]] irb(main):004:0> a.zip(b) { |x| p x } [1, 6] [2, 7] [3, 8] [4, 9] [5, 10] => nil It's those blocks and yield again! Aren't they great? Stick a block after a zip and instead of building a great big array, it yields pairs for you to do what you want with. If you want generators in ruby, just define an "each" method in your class. Remember that for i in STUFF # do things end is just syntactical sugar for STUFF.each do |i| # do things end Here's the standard silly example: the Fibonacci sequence generator. class Fib def fib(x) @@fibs ||= {}; if x <= 0 then return 1 end; return @@fibs[x] ||= fib(x - 2) + fib(x - 1) end # I didn't exactly put much thought into this method, and it shows def each(limit=10000,&block) counter=1 while true r=fib(counter) break if r>limit yield r counter+=1 end end end f=Fib.new # Ruby with a Python accent. "for", a generator, a colon, and the % # string operator! for i in f: puts "%d" % i end --Dave