From: Jerry Blanco Date: 2007-06-15T05:47:08+09:00 Subject: Directory tree traversal fun Hi, I want to write a recursive file renamer. It will work such that given the following: c:\prov\foo1.txt c:\prov\fooDir c:\prov\fooDir\foo2.txt you call rename("c:\\prov", "foo", "bar") and get c:\prov\bar1.txt c:\prov\barDir c:\prov\barDir\bar2.txt I wrote the following: def rename(headOfTree, what, withWhat) p = Pathname.new(headOfTree) p.find() do |file| path = file.to_s #just to make it prettier File.rename(path, path.gsub("#{what}", withWhat)) if path.include?(what) end end The problem is that p.find() is top-to-bottom, so it renames in the following order: 1. c:\prov\bar1.txt 2. c:\prov\barDir Then, it can't get to c:\prov\fooDir anymore, so it doesn't rename c:\prov\fooDir\foo2.txt Is there a more elegant solution than creating an array with the names, sort the array length descending and rename? I don't trust this approach because it could happen that it reverts the order of some files. Is there a way to traverse a directory leaves-first? (bottom-to-top) -- /(bb|[^b]{2})/ <- The question