Go to content Go to menu

Ever want to traverse a directory recursively and do something for each one? Me too. Thanks to Ruby's wonderful functional features, we can separate the traversing algorithm from the code that actually does the interesting work.

def recurse_directory(dir_name, &block)
  Dir.chdir(dir_name) do
    yield
      
    Dir.entries('.').
      select{|e| e != '.' and e != '..'}.
      select{|e| File.directory?(e) }.
      each do |e|
          recurse_over_directory(e, &block)
    end
  end
end

Now, for example, we can use recurse_directory to remove all the .svn directories from a project, thus releasing it from Subversion's stern-yet-gentle grip.

recurse_directory('~/projects/my_project') do
  if Dir.entries('.').detect{|e| e == '.svn' }
    `rm -rf .svn`
  end
end