[ruby] Iterate through every file in one directory

How do I write a loop in ruby so that I can execute a block of code on each file?

I'm new to ruby, and I've concluded that the way to do this is a do each loop.
The ruby file will be executed from a different directory than the directory I want to loop through.

I've tried the Dir.foreach and I couldn't get it to work.

This question is related to ruby directory filesystems

The answer is


Dir has also shorter syntax to get an array of all files from directory:

Dir['dir/to/files/*'].each do |fname|
    # do something with fname
end

Dir.foreach("/home/mydir") do |fname|
  puts fname
end

As others have said, Dir::foreach is a good option here. However, note that Dir::foreach and Dir::entries will always include . and .. (the current and parent directories). You will generally not want to work on them, so you can use Dir::each_child or Dir::children (as suggested by ma11hew28) or do something like this:

Dir.foreach('/path/to/dir') do |filename|
  next if filename == '.' or filename == '..'
  # Do work on the remaining files & directories
end

Dir::foreach and Dir::entries (as well as Dir::each_child and Dir::children) also include hidden files & directories. Often this is what you want, but if it isn't, you need to do something to skip over them.

Alternatively, you might want to look into Dir::glob which provides simple wildcard matching:

Dir.glob('/path/to/dir/*.rb') do |rb_filename|
  # Do work on files & directories ending in .rb
end

The find library is designed for this task specifically: https://ruby-doc.org/stdlib-2.5.1/libdoc/find/rdoc/Find.html

require 'find'
Find.find(path) do |file|
  # process
end

This is a standard ruby library, so it should be available


To skip . & .., you can use Dir::each_child.

Dir.each_child('/path/to/dir') do |filename|
  puts filename
end

Dir::children returns an array of the filenames.


I like this one, that hasn't been mentioned above.

require 'pathname'

Pathname.new('/my/dir').children.each do |path|
    puts path
end

The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.


This is my favorite method for being easy to read:

Dir.glob("*/*.txt") do |my_text_file|
  puts "working on: #{my_text_file}..."
end

And you can even extend this to work on all files in subdirs:

Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
  puts "working on: #{my_text_file}..."
end

Dir.new('/my/dir').each do |name|
  ...
end

Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to directory

Moving all files from one directory to another using Python What is the reason for the error message "System cannot find the path specified"? Get folder name of the file in Python How to rename a directory/folder on GitHub website? Change directory in Node.js command prompt Get the directory from a file path in java (android) python: get directory two levels up How to add 'libs' folder in Android Studio? How to create a directory using Ansible Troubleshooting misplaced .git directory (nothing to commit)

Examples related to filesystems

Get an image extension from an uploaded file in Laravel Notepad++ cached files location No space left on device How to create a directory using Ansible best way to get folder and file list in Javascript Exploring Docker container's file system Remove directory which is not empty GIT_DISCOVERY_ACROSS_FILESYSTEM not set Trying to create a file in Android: open failed: EROFS (Read-only file system) Node.js check if path is file or directory