liveBook · Manning

Dir#entries

As explained in The Well-Grounded Rubyist, Fourth Edition

Dir#entries is a Ruby method that returns the entries of a directory as an array.

Dir#entries returns a directory’s entries as an array. It includes the current-directory entry ("."), parent-directory entry (".."), and hidden names beginning with a period; filter them when needed. section 12.4.1

Use the method when you need the directory contents without glob matching:

  • Call it on a Dir instance, such as d.entries, or through the class method Dir.entries(path). section 12.4.1
  • Filter names beginning with a dot to exclude hidden, current-directory, and parent-directory entries. section 12.4.1
  • Join each name with the directory path before testing files or processing their contents. section 12.4.1
d = Dir.new("/Users/dblack/Devel/ruby-4.0.1/lib/net")
entries = d.entries   1
entries.delete_if {|entry| entry =~ /^\./ } 2
entries.map! {|entry| File.join(d.path, entry) } 3
entries.delete_if {|entry| !File.file?(entry) } 4
print "Total bytes: "

puts entries.inject(0) {|total, entry|total + File.size(entry) } 5

A worked sequence removes dot entries, converts names to full paths, keeps regular files, and sums their sizes. section 12.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains instance and class access, special entries, path construction, filtering, and aggregation without detailing method internals.
Examples
Uses irb listings and a file-size calculation that filters hidden entries and non-regular files.
What it assumes
Assumes familiarity with Ruby objects, arrays, blocks, and basic Dir and File operations.
What you can do after
Apply Dir#entries to inspect a directory and build filtered lists of full file paths.
How it connects
Connects directory entries with Dir, directory globbing, Array filtering, File.join, File.file?, and inject.

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.