在 ruby on rails 中遍历目录和读取文件 [英] Traversing directories and reading from files in ruby on rails
问题描述
我在弄清楚如何 1) 遍历目录和 2) 获取每个文件 (.txt) 并将其另存为字符串时遇到了一些麻烦.我显然对 ruby 和 rails 都很陌生.
I'm having some trouble figuring out how to 1) traverse a directory and 2) taking each file (.txt) and saving it as a string. I'm obviously pretty new to both ruby and rails.
我知道我可以用 f=File.open("/path/*.txt")
保存文件,然后用 puts f.read
输出它但我宁愿将其保存为字符串,而不是 .txt,并且不知道如何为每个文件执行此操作.
I know that I could save the file with f=File.open("/path/*.txt")
and then output it with puts f.read
but I would rather save it as a string, not .txt, and dont know how to do this for each file.
谢谢!
推荐答案
Jake 的回答已经足够好了,但是 each_with_object
会使它稍微短一些.我也让它递归.
Jake's answer is good enough, but each_with_object
will make it slightly shorter. I also made it recursive.
def read_dir dir
Dir.glob("#{dir}/*").each_with_object({}) do |f, h|
if File.file?(f)
h[f] = open(f).read
elsif File.directory?(f)
h[f] = read_dir(f)
end
end
end
当目录是这样的:
--+ directory_a
+----file_b
+-+--directory_c
| +-----file_d
+----file_e
然后
read_dir(directory_a)
会回来:
{file_b => contents_of_file_b,
directory_c => {file_d => contents_of_file_d},
file_e => contents_of_file_e}
这篇关于在 ruby on rails 中遍历目录和读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!