On 17.10.2007 19:36, Luis wrote:
> Hello,
> 
> I am trying to code a method that accepts a block... easy. The problem
> is that this method is recursive, so I don't know how to pass the
> block through the recursive calls.
> 
> The specific code is about recurising through a directory tree while
> calling the provided code block once per each directory, passing the
> list of files in that directory. This is the code:
> 
> class DirInfo
> 
> 	# constructor, etc. removed for clarity
> 
> 	def scan
> 		@path.each_entry do |p|
> 			next if p.to_s == "." || p.to_s == ".."
> 			p = @path + p
> 			if p.file?
> 				finf = FileInfo.new(p)
> 				@files << finf
> 			elsif p.directory?
> 				dinf = DirInfo.new(p)
> 				dinf.scan	# ==> Recursive search of subdirs
> 			end
> 		end
> 		yield @path, @files
> 	end
> 
> end
> 
> 
> So if I do:
> 
> di = DirInfo.new("/devtools/ruby")
> di.scan do |path, files|
> 	puts "Directory #{path} has #{files.length} files"
> end
> 
> I expect to get my block called once per each subdirectory, passing
> the subdir path and list of files in that subdir. The problem is that
> the fisrt time the call scan is made from within scan, no block is
> given, so I get a "no block given" exception and the program stops.
> 
> I know there are other ways to scan directories, but please take it
> just as an example. Still the question is, how to combine
> recursiveness with blocks?

The typical (and IIRC most efficient) idiom is to pass on the block 
parameter:

def foo(&b)
   foo(&b)
end

Another remark: it seems you are reinventing Find.find().  Why do you do 
that?

Kind regards

	robert