要处理目录中的所有文件:
Dir['**/*'].each do |filepath|
# filepath is a string path to the file or directory
# relative from the working directory of the script
end
Run Code Online (Sandbox Code Playgroud)
因此,如果你已经有了,find_text_in_file( some_word, filepath )你可以这样做:
Dir['**/*'].select{|f| File.file?(f) }.each do |filepath|
find_text_in_file( some_word, filepath )
end
Run Code Online (Sandbox Code Playgroud)
请注意,以上将在深度优先遍历中搜索文件。如果你想以广度优先的方式搜索,你可以使用这个:
files = Dir['**/*'].select{ |f| File.file?(f) }
files.sort_by{ |f| f.split(File::SEPARATOR).length }.each do |filepath|
find_text_in_file( some_word, filepath )
end
Run Code Online (Sandbox Code Playgroud)
或者,如果您已经拥有,find_word_in_directory( some_word, dirpath )则可以执行以下操作:
Dir['**/*'].select{ |f| File.directory?(f) }.each do |dirpath|
find_word_in_directory( some_word, dirpath )
end
Run Code Online (Sandbox Code Playgroud)