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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…