From: Brian Candler Date: 2008-12-17T00:17:18+09:00 Subject: Re: implementing python's os.walk Brad Volz wrote: > As some background, python's os.walk() [1] is a generator function. > It is passed the top of a directory tree and it returns the following > for each subdirectory that it encounters: > . the working directory > . an Array of subdirectories > . an Array of non-directory files The normal 'ruby way' to do this would be as an object which *yields* each of these things in turn, rather than returning them. In many cases you can use it directly like this. If you want to turn it into a generator you can wrap it using generator.rb; or more cleanly in ruby 1.9, turn it into an Enumerator, which has this functionality built in. class Foo def all_dirs yield "dir1" yield "dir2" yield "dir3" end end foo = Foo.new # Normal style foo.all_dirs { |x| p x } # Generator style (ruby 1.9, uses Fiber) g = foo.to_enum(:all_dirs) 3.times { p g.next } # Generator style (ruby 1.8, beware uses callcc) require 'generator' require 'enumerator' g = Generator.new(foo.to_enum(:all_dirs)) 3.times { p g.next } -- Posted via http://www.ruby-forum.com/.