gpt4 book ai didi

ruby-on-rails - Ruby:遍历目录和文件

转载 作者:数据小太阳 更新时间:2023-10-29 08:58:25 28 4
gpt4 key购买 nike

我编写了以下脚本来遍历目录、子目录及其文件:

    def self.search_files_in_dir_for(dir, strings)
results = {}
puts "Initializing test ..."
Dir.foreach(dir) do |file|
next if file == '.' or file == '..'
puts 'TEST: Testing dir "' + dir + "/" + file + '"'
if File.file?(file)
puts 'TEST: Testing "' + dir + "/" + file + '"'
line_number = 0
IO.foreach(file) do |line|
line_number = line_number + 1
if strings.any? { |string| line.include?(string) }
string = strings.detect { |string| line.include?(string) }
puts source = file + ":" + line_number.to_s
results[source] = string
end
end
elsif File.directory?(file)
# Search child directories
search_files_in_dir_for(File.join(dir, file), strings)
end
end
end

给定以下目录+文件结构:

- views
- application
- abcdefg
- _partial2.html.erb
- _partial1.html.erb
- layouts
- application.html.erb

当将 views 目录的路径作为 dir 传递时,我得到了输出:

Initializing test ...
TEST: Testing dir "views/application"
TEST: Testing dir "views/layouts"

我希望是这样的:

Initializing test ...
TEST: Testing dir "views/application"
TEST: Testing dir "views/application/abcdefg"
TEST: Testing "views/application/abcdefg/_partial2.html.erb"
TEST: Testing "views/application/_partial1.html.erb"
TEST: Testing dir "views/layouts"
TEST: Testing "views/layouts/application.html.erb"

我在那个脚本中做错了什么?

最佳答案

路径名#Glob

明显较短的版本,使用 PathnamePathname.glob :

require 'pathname'
files, dirs = Pathname.glob('**/*').partition(&:file?)

它给你两个数组:一个包含当前目录中的所有文件,另一个包含所有子文件夹。

对于特定的目录:

files, dirs = Pathname.glob(File.join(dir, '**/*')).partition(&:file?)

你只需要解析文件的内容

Grep 还是 ack?

看起来您正在尝试复制 grep , ackgit grep

您的代码,已修复

这是您的代码的修改版本。最大的问题是 file 是一个相对路径。 File.file?(file) 总是返回 false :

@results = {}
def search_files_in_dir_for(dir, strings)
Dir.foreach(dir) do |file|
complete_path = File.join(dir, file)
next if file == '.' or file == '..'
if File.file?(complete_path)
puts "TEST: Testing '#{complete_path}'"
line_number = 0
IO.foreach(complete_path) do |line|
line_number = line_number + 1
if strings.any? { |string| line.include?(string) }
string = strings.detect { |string| line.include?(string) }
source = complete_path + ":" + line_number.to_s
@results[source] = string
end
end
else
# Search child directories
search_files_in_dir_for(complete_path, strings)
end
end
end

search_files_in_dir_for(..., [..., ...])

p @results

关于ruby-on-rails - Ruby:遍历目录和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867187/

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