gpt4 book ai didi

ruby - 以递归方式遍历目录和子目录,在 ruby​​ 中显示 'path/file'

转载 作者:行者123 更新时间:2023-12-04 02:09:33 28 4
gpt4 key购买 nike

我使用下面的代码递归遍历目录和子文件夹的文件:

Dir.glob("**/*").each do |file|

filename = "#{File.basename(file)}"
output = `git log -1 -r -n 1 --pretty=format:\"%h: #{filename}\" -- #{filename}`

end

我从这次迭代中得到的结果如下所示:
Actual Output:
<The format I choose>: folder1
<The format I choose>: a_file
<The format I choose>: folder2
<The format I choose>: a_file
<The format I choose>: another_file
<The format I choose>: folder3
<The format I choose>: a_file

而我想要的表格在下面。
Expected Output:
<The format I choose>: folder1/a_file
<The format I choose>: folder2/a_file
<The format I choose>: folder2/another_file
<The format I choose>: folder3/a_file

你能指出并解释我在循环中的错误吗?

最佳答案

基本上原因是你正在运行 File.basename它为您提供文件的“基本名称”而不是相对路径。

另外 .glob("**/*")还包括目录,因此您需要考虑到这一点。

这就是我要做的...

Dir.glob("**/*").each do |file|
next if File.directory?(file) # skip the loop if the file is a directory
puts file
output = `git log -1 -r -n 1 --pretty=format:"%cd [%h]" -- #{file}`
puts output
end

如果你想让我解释上面代码中的任何一行,请告诉我......

关于ruby - 以递归方式遍历目录和子目录,在 ruby​​ 中显示 'path/file',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40016856/

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