As others have said, Dir.foreach
is a good option here. However, note that Dir.entries
and Dir.foreach
will always show .
and ..
(the current and parent directories). You will generally not want to work on them, so you can do something like this:
Dir.foreach('/path/to/dir') do |item|
next if item == '.' or item == '..'
# do work on real items
end
Dir.foreach
and Dir.entries
also show all items in the directory - hidden and non-hidden alike. Often this is what you want, but if it isn't, you need to do something to skip over the hidden files and directories.
Alternatively, you might want to look into Dir.glob
which provides simple wildcard matching:
Dir.glob('/path/to/dir/*.rb') do |rb_file|
# do work on files ending in .rb in the desired directory
end