遍历一个目录中的每个文件 [英] Iterate through every file in one directory
问题描述
如何在 ruby 中编写一个循环,以便我可以对每个文件执行一段代码?
How do I write a loop in ruby so that I can execute a block of code on each file?
我是 ruby 的新手,我得出的结论是,这样做的方法是一个 do each 循环.
ruby 文件将从与我要循环的目录不同的目录中执行.
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.
我已经尝试了 Dir.foreach
但我无法让它工作.
I've tried the Dir.foreach
and I couldn't get it to work.
推荐答案
正如其他人所说,Dir::foreach
在这里是一个不错的选择.但是,请注意 Dir::foreach
和 Dir::entries
将始终包括 .
和 ..
(当前和父目录).您通常不想处理它们,因此您可以使用 目录::each_child
或 目录::children
(如 ma11hew28 建议)或执行以下操作:
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
和 Dir::entries
(以及 Dir::each_child
和 Dir::children
) 还包括隐藏文件 &目录.通常这就是您想要的,但如果不是,您需要做一些事情来跳过它们.
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.
或者,您可能需要查看 Dir::glob
提供简单的通配符匹配:
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
这篇关于遍历一个目录中的每个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!