Question

Get All File Names from a Folder in Ruby

rubyfiledirectoryfilenames

Question

I want to retrieve the names of all files in a folder using Ruby.

Short Answer

By the end of this page, you will understand how Ruby reads directory contents, how to list file names from a folder, how to filter out directories, and which Ruby methods are commonly used for this task in real programs.

Concept

In Ruby, working with files and folders is usually done with the built-in Dir and File classes.

If you want all file names from a folder, the main idea is:

  • read the directory entries
  • decide whether you want everything or only files
  • optionally build full paths
  • optionally filter out special entries like . and ..

A folder can contain:

  • regular files
  • subdirectories
  • hidden files
  • special entries such as . and ..

That means "get all file names" can mean different things depending on your goal:

  • list every entry in the directory
  • list only regular files
  • list files matching a pattern such as *.txt
  • list files recursively from nested folders

This matters in real programming because many applications need to inspect folders:

  • import data files
  • process uploaded documents
  • scan log directories
  • load configuration files
  • generate reports from many files

Ruby gives you a few clean ways to do this. The most common are:

  • Dir.entries(path)
  • Dir.children(path)
  • Dir.glob(pattern)
  • filtering with File.file?(path)

For beginners, Dir.children is often the easiest starting point because it returns the names inside a folder without including . and ...

Mental Model

Think of a folder like a drawer in a cabinet.

  • Dir.entries opens the drawer and tells you everything inside, including the special labels . and ..
  • Dir.children opens the drawer and shows only the actual visible items
  • File.file? helps you check whether an item is a document instead of another drawer
  • Dir.glob is like saying, "Show me only items whose labels match this pattern"

So the process is:

  1. open the drawer
  2. look at each item
  3. keep only the ones you need
Take Quiz

Syntax and Examples

The most common ways to list file names in Ruby are shown below.

1. List all entries in a folder

files = Dir.entries("my_folder")
puts files

This returns entries such as:

[".", "..", "file1.txt", "file2.txt"]

Dir.entries includes . and .., so you often need to remove them.

2. List children without . and ..

files = Dir.children("my_folder")
puts files

This usually returns cleaner results:

["file1.txt", "file2.txt", "images"]

3. Get only regular files

folder = "my_folder"
files = Dir.children(folder).select do |name|
  File.file?(File.join(folder, name))
end

puts files

Why this works

  • Dir.children(folder) gets the names inside the folder
  • File.join(folder, name) creates the full path safely
  • File.file?(...) keeps only real files, not subdirectories

4. Get files matching a pattern

txt_files = Dir.glob("my_folder/*.txt")
puts txt_files

This returns matching paths, for example:

["my_folder/a.txt", "my_folder/b.txt"]

If you only want the base file names:

txt_file_names = Dir.glob("my_folder/*.txt").map do |path|
  File.basename(path)
end

puts txt_file_names

5. Read files recursively

files = Dir.glob("my_folder/**/*").select do |path|
  File.file?(path)
end

puts files

This looks through subfolders too.

Step by Step Execution

Consider this example:

folder = "docs"
files = Dir.children(folder).select do |name|
  File.file?(File.join(folder, name))
end

puts files

Assume the docs folder contains:

report.pdf
notes.txt
images

Step by step:

  1. folder = "docs"

    • A variable stores the folder name.
  2. Dir.children(folder)

    • Ruby reads the contents of docs.
    • It returns something like:
      ["report.pdf", "notes.txt", "images"]
      
  3. .select do |name| ... end

    • Ruby checks each entry one by one.
    • select keeps only the entries where the block returns true.
  4. First entry: "report.pdf"

    • File.join(folder, name) becomes:
      "docs/report.pdf"
      
    • File.file?("docs/report.pdf") returns true
    • Ruby keeps it.
  5. Second entry: "notes.txt"

    • Full path becomes "docs/notes.txt"
    • File.file? returns true
    • Ruby keeps it.
  6. Third entry: "images"

    • Full path becomes "docs/images"
    • If images is a folder, File.file? returns false
    • Ruby removes it.
  7. Final result:

["report.pdf", "notes.txt"]
  1. puts files
    • Ruby prints each file name.

Real World Use Cases

Here are common situations where this is useful:

Processing uploaded files

A script may scan an uploads folder and process each image or document.

Dir.children("uploads").each do |name|
  path = File.join("uploads", name)
  next unless File.file?(path)

  puts "Processing #{name}"
end

Importing CSV files

A data import job may look for all .csv files in a directory.

csv_files = Dir.glob("imports/*.csv")

Reading log files

A maintenance script may gather all log file names before compressing them.

log_files = Dir.glob("logs/*.log")

Loading configuration files

An app may load all Ruby config files from a config folder.

config_files = Dir.glob("config/*.rb")

Building a file index

A search tool may scan a folder and store file names in a database.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just list names.

Common patterns

Filter early

Only keep valid files before doing more work.

Dir.children(folder).each do |name|
  path = File.join(folder, name)
  next unless File.file?(path)

  # process file
end

This is a guard clause pattern using next.

Use File.join instead of manual string building

path = File.join(folder, name)

This is safer than:

path = folder + "/" + name

Use glob patterns for file types

json_files = Dir.glob(File.join(folder, "*.json"))

This makes code easier to read when you only want certain file extensions.

Handle missing directories

unless Dir.exist?(folder)
  puts "Folder does not exist"
  return
end

Real applications often validate the path before reading it.

Convert paths to file names when needed

Some methods return full paths, but UI code may only need the visible file name.

names = Dir.glob("uploads/*").map { |path| File.basename(path) }

Recursive scans for nested structures

Projects that work with assets, templates, or logs often scan subfolders too.

all_files = Dir.glob("assets/**/*").select { |path| File.file?(path) }

Common Mistakes

Beginners often run into a few predictable issues.

1. Forgetting that Dir.entries includes . and ..

Broken expectation:

files = Dir.entries("my_folder")
puts files

You may see:

[".", "..", "file1.txt"]

Use Dir.children if you do not want those special entries.

files = Dir.children("my_folder")

2. Treating directories as files

Broken code:

Dir.children("my_folder").each do |name|
  puts File.read(name)
end

Problem:

  • name is not the full path
  • some entries may be directories

Better:

folder = "my_folder"
Dir.children(folder).each do |name|
  path = File.join(folder, name)
  next unless File.file?(path)

  puts File.read(path)
end

3. Building paths manually

Less safe:

path = folder + "/" + name

Better:

path = File.join(folder, name)

4. Assuming Dir.glob returns only file names

files = Dir.glob("my_folder/*.txt")

This returns paths like:

["my_folder/a.txt"]

If you only want the name:

names = Dir.glob("my_folder/*.txt").map { |path| File.basename(path) }

5. Not handling a missing folder

Broken code:

files = Dir.children("missing_folder")

This can raise an error.

Safer version:

folder = "missing_folder"
if Dir.exist?(folder)
  files = Dir.children(folder)
else
  puts "Folder not found"
end

6. Confusing hidden files with normal files

Some systems have hidden files like .env or .gitignore. Depending on your method and pattern, these may or may not appear, so always test your specific case.

Comparisons

Here is how the main options differ.

MethodReturnsIncludes . and ..Best for
Dir.entries(path)All entriesYesLow-level directory listing
Dir.children(path)Child namesNoClean listing of names
Dir.glob("path/*")Matching pathsNoPattern matching
Dir.glob("path/**/*.txt")Recursive matchesNoRecursive searches

Dir.children vs Dir.entries

  • Use Dir.children when you want cleaner results.
  • Use Dir.entries when you explicitly need every entry, including special ones.

Dir.children vs Dir.glob

  • Use Dir.children when you want all names in one folder.
  • Use Dir.glob when you want pattern matching like *.rb or recursive searching.

Names vs full paths

NeedBetter choice
Just file namesDir.children(path)
Full matching pathsDir.glob(pattern)
Only regular filesDir.children(path) + File.file?
Take Quiz

Cheat Sheet

# All entries, including "." and ".."
Dir.entries("folder")

# Names inside folder, excluding "." and ".."
Dir.children("folder")

# Only regular files in a folder
Dir.children("folder").select do |name|
  File.file?(File.join("folder", name))
end

# Files matching a pattern
Dir.glob("folder/*.txt")

# Recursive file search
Dir.glob("folder/**/*").select { |path| File.file?(path) }

# Get file name from full path
File.basename("folder/test.txt")

# Safely build paths
File.join("folder", "test.txt")

# Check whether a directory exists
Dir.exist?("folder")

Quick rules

  • Dir.entries includes . and ..
  • Dir.children does not include . and ..
  • Dir.glob is best for pattern matching
  • File.file?(path) checks whether something is a regular file
  • Use File.join instead of manually adding /
  • Use File.basename when you want just the name from a path

FAQ

How do I get all file names from a folder in Ruby?

Use Dir.children(folder) to get names inside a folder. If you want only regular files, filter with File.file?.

What is the difference between Dir.entries and Dir.children in Ruby?

Dir.entries includes the special entries . and .., while Dir.children excludes them.

How do I get only files and not subdirectories in Ruby?

Use:

Dir.children(folder).select { |name| File.file?(File.join(folder, name)) }

How do I list only .txt files in a Ruby folder?

Use a glob pattern:

Dir.glob("folder/*.txt")

How do I get file names without the folder path in Ruby?

Use File.basename:

Dir.glob("folder/*.txt").map { |path| File.basename(path) }

Can Ruby list files recursively in subfolders?

Yes. Use Dir.glob with **:

Dir.glob("folder/**/*").select { |path| File.file?(path) }

What happens if the folder does not exist?

Ruby may raise an error when you try to read it. Check first with Dir.exist?(folder).

Take Quiz

Mini Project

Description

Build a small Ruby script that scans a folder and prints only the names of regular files. This demonstrates directory reading, path building, and filtering out subdirectories.

Goal

Create a script that lists only file names from a chosen folder and ignores directories.

Requirements

  • Store the folder path in a variable.
  • Check that the folder exists before reading it.
  • Read the folder contents.
  • Filter out anything that is not a regular file.
  • Print each file name on its own line.
Take Quiz

Keep learning

Related questions

View more