在Ruby中递归迭代目录及其子目录,并显示每个文件的相对路径。

4
我正在使用以下代码递归地迭代目录和子文件夹中的文件:
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

你能指出并解释一下我的循环错误吗?


你能完成问题顶部的代码吗?也就是在“.each do |file|”之后的部分。 - Ismail Moghul
@IsmailM,我加入了代码。 - hack-is-art
请告诉我我的回答是否解决了您的问题 - 如果是,请将问题标记为已解决。 - Ismail Moghul
1个回答

5

基本上原因是你正在运行 File.basename,它会返回文件的“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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接