How to Use Dir.glob in Ruby

09/21/2021

Contents

In this article, you will learn how to use Dir.glob in Ruby.

Using Dir.glob

Dir.glob is a method in Ruby’s Dir class that is used to match files and directories against a pattern. The pattern is typically specified using a wildcard character *, which can match any sequence of characters.

Here’s an example of how to use Dir.glob to match all .txt files in the current directory:

Dir.glob("*.txt") do |file|
  puts file
end

This will output the names of all .txt files in the current directory.

You can also specify a path to search for files in a specific directory. For example, to match all .rb files in the lib directory:

Dir.glob("lib/**/*.rb") do |file|
  puts file
end

The ** syntax matches all directories and subdirectories recursively, so this will match all .rb files in the lib directory and any subdirectories under it.

Dir.glob returns an array of file names that match the pattern, so you can also assign the result to a variable:

files = Dir.glob("*.txt")
puts files.inspect

This will output an array of file names that match the pattern.