迭代一个目录中的每个文件 [英] Iterate through every file in one directory
问题描述
我是Ruby的新手,得出结论,做这个的方法是每个循环。
ruby文件将从与我想循环的目录不同的目录执行。
我尝试过 Dir.foreach
,我无法让它工作。
正如其他人所说, Dir.foreach
是一个很好的选择。但是请注意, Dir.entries
和 Dir.foreach
将始终显示。
和 ..
(当前和父目录)。你通常不想在他们身上工作,所以你可以这样做:
Dir.foreach('/ path / to / dir')do | item |
next if item =='。'或item =='..'
#在实际项目上工作
end
Dir.foreach
和 Dir.entries
还显示全部目录中的项目 - 隐藏和非隐藏。通常这是你想要的,但如果不是,你需要做一些事来跳过隐藏的文件和目录。
或者,你可能想看看进入 Dir.glob
提供简单的通配符匹配:
Dir.glob('/ path / to / dir / *。rb' )do | rb_file |
#在所需目录中以.rb结尾的文件执行
end
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.
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
这篇关于迭代一个目录中的每个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!