递归地迭代目录和子目录,在 ruby​​ 中显示“路径/文件”

hac*_*art 4 ruby recursion loops

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

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

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

end
Run Code Online (Sandbox Code Playgroud)

我从这次迭代中得到的结果如下所示:

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
Run Code Online (Sandbox Code Playgroud)

而我想要的表格如下。

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
Run Code Online (Sandbox Code Playgroud)

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

Ism*_*hul 5

基本上原因是您正在运行,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
Run Code Online (Sandbox Code Playgroud)

如果您希望我解释上面代码中的任何一行,请告诉我......