Reason #73 • March 14th, 2026

Globbing files with Dir.glob

Somehow using Dir.glob is one of the most satisfying methods to invoke in Ruby to me. Like squeezing a stress ball, it just feels good every time, definitely r/oddlysatisfying material.

Dir.glob returns a list of file paths matching a specified pattern. Here are some examples run from within the Loving Ruby codebase, a simple Rails app:

Ruby
# Find all initializers
Dir.glob("config/initializers/*.rb")
# => [
# "config/initializers/assets.rb",
# "config/initializers/content_security_policy.rb",
# "config/initializers/filter_parameter_logging.rb",
# "config/initializers/inflections.rb",
# ]

# Find all png files under public, note the recursive glob pattern
Dir.glob("public/**/*.png")
# => [
#  "public/icon.png",
#  "public/images/14-partition-review.png",
#  "public/papercraft.png",
# ]

# Find all YAML files in the codebase
Dir.glob("**/*.yml")
# => [
#  "config/bundler-audit.yml",
#  "config/database.yml",
#  "config/deploy.yml",
#  "config/locales/en.yml",
# ]

# Find all files starting with the letter "c" (spoiler alert!)
Dir.glob("**/c*.*")
# => [
#   "config/ci.rb",
#   "config/credentials.yml.enc",
#   "config/initializers/content_security_policy.rb",
#   "config.ru",
#   "db/ideas/gems/concurrent-ruby.md",
#   "db/ideas/introspection/caller.md",
#   "db/ideas/learnt-from-other-languages/clojure-love-the-basic-datatypes.md",
# ]
    

There are additional glob patterns available, such as ? for matching any single character, {word1,word2} for matching either word, and [a-z] for matching characters in a set. Refer to the Ruby documentation for more details.

A shorthand for Dir.glob is Dir[], so when you're in an IRB session and feeling lazy, you can do Dir["pattern"] as well.

I was going to compare it with JavaScript, but the equivalent functionality would take up too much scroll real estate, so I digressed 😅

History

Dir.glob has been part of Ruby since its inception. It borrows its design from the glob functionality in Unix shells, which allows users to specify patterns for matching file names using the same * wildcard syntax.

It may also have been inspired by the glob method in Perl, which provides similar functionality for matching file names based on patterns.