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.
1 |
require 'find' |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def find_directories(pwd = Dir.pwd) directories = [] begin Find.find(pwd) do |path| Find.prune if path.include? '.git' next unless File.directory?(path) directories << path end rescue puts "Error reading files." end directories end |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def find_files(pwd = Dir.pwd) files = [] begin Find.find(pwd) do |path| Find.prune if path.include? '.git' next if path.include? 'picasa' next unless File.file?(path) files << path end rescue puts "Error reading files." end files end |
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!
There is 1 comment on this post
using ruby 2.2.7: require 'find', "undefined method prune for File::Class(NoMethodError)