Ruby Directory Glob Recursive on Absolute Path

Ruby Directory Glob Recursive on Absolute Path

I'm trying to get the Dir.glob of an absolute path:

path = "/Users/ken/templates"
scaffold = Dir.glob("#{path}/*.erb", File::FNM_DOTMATCH)
p scaffold.inspect

This is my directory structure:

/Users/ken/templates/test.erb
/Users/ken/templates/test2.erb
/Users/ken/templates/app/one.erb
/Users/ken/templates/app/two.erb

When I run on the directory I only get the files in the root of the directory:

"[\"/Users/ken/farmstead/test.erb\", \"/Users/ken/farmstead/test2.erb\"]"

But no entries for the app subdirectory.

How do I get the Glob to go recursive on the absolute path?

2 Answers

To get into subdirectories, one needs to instruct Dir#glob to get into subdirectories:

#                            ⇓⇓⇓
scaffold = Dir.glob("#{path}/**/*.erb", File::FNM_DOTMATCH)

Quote from the documentation I linked:

**
    Matches directories recursively.

2

A cleaner way to tell glob about the absolute directory is to use the base parameter like so:

Dir.glob("**/*.erb", base: path)

Source:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.