A Discursion into Recursion

This program needs to be able to navigate down the entire subdirectory tree to any number of levels. To be able to do this, you have to use recursion. Put simply, a recursive method is one that calls itself. If you aren’t familiar with recursive programming, see Digging Deeper in Digging Deeper.

In the program file_info.rb, the processfiles method is recursive:

file_info.rb

def processfiles( aDir ) totalbytes = 0 Dir.foreach( aDir ){ |f| mypath = "#{aDir}\\#{f}" s = "" if File.directory?(mypath) then if f != '.' and f != '..' then bytes_in_dir = processfiles(mypath) # <==== recurse! puts( "<DIR> ---> #{mypath} contains [#{bytes_in_dir/1024}] KB" ) end else filesize = File.size(mypath) totalbytes += filesize puts ( "#{mypath} ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.