gpt4 book ai didi

ruby - 如何遍历两个目录

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:19 25 4
gpt4 key购买 nike

我怀疑这就是为什么我可能会通过文件比较多次执行文件的原因

我有两个目录:directory1 包含文件 foo.txtbar.txtdirectory2 包含文件 foo.txtbar.txt

def process(directory1, directory2)
Dir.foreach(directory1) do |file1|
Dir.foreach(directory2) do |file2|
puts file1 + file2
end
end
end

当我运行它时,我得到:

..
...
.foo.txt
.bar.txt
...
....
..foo.txt
..bar.txt
foo.txt.
foo.txt..
foo.txtfoo.txt
foo.txtbar.txt
bar.txt.
bar.txt..
bar.txtfoo.txt
bar.txtbar.txt

它应该只打印四个名字。我的循环错了吗?

最佳答案

要回答标题中的实际问题,您可以使用 Dir::[] 遍历 2 个目录例如

Dir['/directory1/*','/directory2/*'] 

这将返回直接位于 /directory1/directory2 下的文件和目录的 Array此外,这将忽略点文件。

参见 Dir#glob用于其他模式选项,例如递归 (**)。

关于ruby - 如何遍历两个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35993819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com