I'm trying to write some ruby that would recursively search a given directory for all empty child directories and remove them.
Thoughts?
Note: I'd like a script version if possible. This is both a practical need and a something to help me learn.
I'm trying to write some ruby that would recursively search a given directory for all empty child directories and remove them.
Thoughts?
Note: I'd like a script version if possible. This is both a practical need and a something to help me learn.
just like the first example, but the first example doesn't seem to handle the recursive bit. The sort and reverse ensures we deal with the most nested directories first.
I suppose sort.reverse could be written as
sort {|a,b| b <=> a}
for efficiencyLooking at the examples from kch, dB. and Vishnu above, I've put together a one-liner that I think is a more elegant solution:
I use
'**/'
instead of'/**/*'
for the glob, which only returns directories, so I don't have to test whether it's a directory later. I'm usingreverse_each
instead ofsort.reverse.each
as it's shorter and supposedly more efficient, according to this post. I preferDir.entries(d).size == 2
to(Dir.entries(d) - %w[ . .. ]).empty?
because it's a little easier to read and understand, although(Dir.entries(d) - %w[ . .. ]).empty?
would probably work better if you had to run your script on Windows.I've tested this quite a bit on Mac OS X and it works well, even with recursive empty directories.
In ruby: