How to List Files in a Directory in Ruby: Simple Guide
In Ruby, you can list files in a directory using
Dir.entries or Dir.glob. For example, Dir.entries(".") returns all files and folders in the current directory as an array.Syntax
Dir.entries(path) returns an array of all files and folders in the given path, including . (current directory) and .. (parent directory).
Dir.glob(pattern) returns an array of files matching the pattern, which can include wildcards like * for flexible matching.
ruby
Dir.entries(path) # Lists all entries in the directory including '.' and '..' Dir.glob(pattern) # Lists files matching the pattern, e.g., '*.rb' for Ruby files
Example
This example lists all files and folders in the current directory using Dir.entries, then lists only Ruby files using Dir.glob.
ruby
puts "All entries in current directory:" puts Dir.entries(".") puts "\nOnly Ruby files in current directory:" puts Dir.glob("*.rb")
Output
All entries in current directory:
.
..
file1.rb
file2.txt
script.rb
Only Ruby files in current directory:
file1.rb
script.rb
Common Pitfalls
One common mistake is forgetting that Dir.entries includes . and .., which represent the current and parent directories. This can cause confusion if you only want actual files.
Another pitfall is using Dir.glob without a pattern, which returns an empty array. Always provide a pattern like * to match files.
ruby
wrong = Dir.entries(".") - [".", ".."] # Correct way to exclude '.' and '..' right = Dir.glob("*") # Lists all files and folders except '.' and '..' puts "Entries excluding '.' and '..':" puts wrong puts "Entries using Dir.glob('*'):" puts right
Output
Entries excluding '.' and '..':
file1.rb
file2.txt
script.rb
Entries using Dir.glob('*'):
file1.rb
file2.txt
script.rb
Quick Reference
| Method | Description | Example |
|---|---|---|
| Dir.entries(path) | Lists all entries including '.' and '..' | Dir.entries(".") |
| Dir.glob(pattern) | Lists files matching pattern, excludes '.' and '..' | Dir.glob("*.rb") |
| Exclude '.' and '..' | Remove current and parent directory entries | Dir.entries(".") - ['.', '..'] |
Key Takeaways
Use Dir.entries(path) to get all files and folders including '.' and '..'.
Use Dir.glob(pattern) to list files matching a pattern without '.' and '..'.
Exclude '.' and '..' manually if using Dir.entries and you want only real files.
Dir.glob('*') lists all files and folders except '.' and '..'.
Always provide a pattern to Dir.glob to get meaningful results.