liveBook · Manning

Dir.glob

As explained in The Well-Grounded Rubyist, Fourth Edition

Dir.[] is Ruby's index-style directory globbing method for returning pathnames matching a glob pattern.

Dir.glob returns pathnames matching a glob pattern. Its index-style spelling, Dir[pattern], is equivalent to calling Dir.glob(pattern). section 12.4.1

Match header files

Dir["/Users/dblack/Devel/ruby-4.0.1/include/ruby/r*.h"] returns the matching header pathnames, such as ractor.h, random.h, and ruby.h. section 12.4.1

Use directory globbing when you need:

  • Wildcard matching, such as Dir["*info*"], rather than every directory entry. section 12.4.1
  • Recursive matching in subdirectories. section 12.4.1
  • A compact replacement for collecting entries, joining full paths, filtering regular files, and summing their sizes. section 12.4.1

Sum matching regular files

dir = "/Users/dblack/Devel/ruby-4.0.1/lib/net" entries = Dir["#{dir}/*"].select { |entry| File.file?(entry) } puts entries.inject(0) { |total, entry| total + File.size(entry) } section 12.4.1

Unlike Dir.entries, globbing omits hidden entries by default, including names beginning with a period on UNIX-like systems. A matching flag can include them: my_directory.glob("*info*", File::FNM_DOTMATCH). section 12.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains syntax, aliases, wildcard and recursive matching, hidden-entry behavior, and a compact aggregation example.
Examples
Uses header-file matching, hidden-file matching, and summing sizes of regular files.
What it assumes
Assumes familiarity with directory entries, arrays, blocks, and File predicates while introducing compact glob-based selection.
What you can do after
Apply it via Ruby's Dir API to find matching pathnames and feed selected files into later operations.
How it connects
Connects directory globbing with Dir.entries, File.file?, File.join, File.size, and File::FNM_DOTMATCH.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.