我怀疑这就是为什么我可能会通过文件比较多次执行文件的原因
我有两个目录:directory1
包含文件 foo.txt
和 bar.txt
,directory2
包含文件 foo.txt
和 bar.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/