Tag Archives: code

Poetic Ruby Method

Here is a limerick for you.

Goodnight.

Using Ruby Find To Look For Files

It’s only been a few months since I started learning Ruby, and I’ve found myself using Find more than any other standard library. It’s likely because I’m mostly doing scripting work to organize my files. If you’re also new to Ruby, you might not know about the Find library and its ability to seek out all files and folders recursively.

The core library’s Dir class has ‘Dir.entries’, but you only get an array of the files and folders in that top directory. When trying to interact with a lot of files in multiple directories, Find is your friend.

This little method will return an array of all the directories within the program’s pwd(present working directory) or any directory supplied to the method. Find has a ::prune method that stops looking any further into the given directory. It’s perfect for ignoring the .git folder incase find comes across any repositories.

This ‘find_files’ method is almost identical, but it finds files instead of directories. I know, very self explanatory, but I included this code here to point out something that came up when I first ran it. Most of my photo library comes from my Windows machine. I used Google Picasa for organizing, which makes a little hidden file inside any folder containing an image. Never really matters until you’re making a script to compare and move around some photos! Skipping any file path containing the word “picasa” fixes the problem easily.

I’ve found this useful quite a few times in both repeated use and one-time-use scripts. This technique could also be modified to return a hash instead of an array, containing extra metadata about each file. The returned info can be used in any number of ways, whether the desire is information or alteration.

I’ve had a lot of fun making simple scripts and command line tools. I write this in the hopes that a fellow budding Rubyist can be inspired to write fun scripts for their system. Please feel free to leave a comment, I’d love to hear about any cool things you’ve done with Find!