遍历一个目录中的每个文件
如何在 ruby 中编写循环以便可以在每个文件上执行代码块?
我是 ruby 新手,我得出的结论是,执行此操作的方法是执行每个循环。
ruby 文件将从与我想要循环的目录不同的目录中执行。
我尝试过 Dir.foreach
但无法让它工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
正如其他人所说,
Dir::foreach
< /a> 在这里是一个不错的选择。但是,请注意Dir::foreach
和 < code>Dir::entries 将始终包含.
和..
(当前目录和父目录)。您通常不想处理它们,因此您可以使用Dir::each_child
或目录::children
(如ma11hew28建议)或执行以下操作:Dir::foreach
和Dir::entries
(以及Dir::each_child
和Dir::children
)还包括隐藏文件和目录。通常这是您想要的,但如果不是,您需要采取一些措施来跳过它们。或者,您可能需要查看
Dir::glob
提供简单的通配符匹配:
As others have said,
Dir::foreach
is a good option here. However, note thatDir::foreach
andDir::entries
will always include.
and..
(the current and parent directories). You will generally not want to work on them, so you can useDir::each_child
orDir::children
(as suggested by ma11hew28) or do something like this:Dir::foreach
andDir::entries
(as well asDir::each_child
andDir::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:这是我最喜欢的易于阅读的方法:
您甚至可以扩展它以适用于子目录中的所有文件:
This is my favorite method for being easy to read:
And you can even extend this to work on all files in subdirs:
Dir 还具有更短的语法来从目录中获取所有文件的数组:
Dir has also shorter syntax to get an array of all files from directory:
find 库是专门为此任务而设计的:
https://ruby-doc.org/stdlib- 2.5.1/libdoc/find/rdoc/Find.html
这是一个标准的 ruby 库,所以它应该可用
The find library is designed for this task specifically:
https://ruby-doc.org/stdlib-2.5.1/libdoc/find/rdoc/Find.html
This is a standard ruby library, so it should be available
跳过
.
&..
,您可以使用Dir ::each_child
。Dir::children
返回一个文件名数组。To skip
.
&..
, you can useDir::each_child
.Dir::children
returns an array of the filenames.我喜欢这个,上面没有提到。
好处是你得到一个 Pathname 对象而不是字符串,你可以用它做有用的事情并进一步遍历。
I like this one, that hasn't been mentioned above.
The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.