Showing posts with label ruby directory recursive print. Show all posts
Showing posts with label ruby directory recursive print. Show all posts

Monday, January 12, 2009

Recursing through Directories in Ruby

I was trying to print the directories and files recursively, this task was daunting, for me, in Ruby, as I am from Java. I was trying to do the same way that the way we do it in Java. During this course of time, I tried in several ways. Now, the way I implemented is different, Ruby way.

Here our task is to print only the files and its size. In ruby, the code is as follows.

require 'FileUtils'
class DirectoryProbe
def self.print_all_files filename
if File.directory?(filename)
Dir.chdir(filename)
files = Dir['**/*']
files.each{ |file|
unless File.directory?(file)
puts "#{file} \t #{File.size(file)} bytes"
end
}
end
end
end


Dir.chdir(file) issues a command cd in windows and linux. The code Dir['**/*'] returns the array containing all the files in the directory recursively. After that I work on each file separately.