Ruby - 打印一个哈希到txt文件 [英] Ruby - Printing a hash to txt file
本文介绍了Ruby - 打印一个哈希到txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要将每个关键字作为文件名和每个关键字的值作为每个文件的内容,将以下散列值打印到txt文件中。
hash
{'a'=> ['abc','def','ghi'],'b'=> ['jkl','mno','pqr']}
输出文件应该包含以下内容格式
a.txt
abc
def
ghi
b.txt
jkl
mno
pqr
想知道如何去解决这个问题? ['abc','def','ghi'],'b'=> ['jkl','mno','pqr']}
hash.each do | k,v |
File.open(#{k} .txt,'w'){| f | f.puts v}
end
Need to print the following hash into a txt files with each key as the file name and each key's values as the content for each file.
hash
{ 'a' => [ 'abc' , 'def', 'ghi'] , 'b' => [ 'jkl' , 'mno' , 'pqr' ] }
The output files shall have the following format
a.txt
abc
def
ghi
b.txt
jkl
mno
pqr
Wondering how to go about this?
解决方案
hash = { 'a' => [ 'abc' , 'def', 'ghi'] , 'b' => [ 'jkl' , 'mno' , 'pqr' ] }
hash.each do |k,v|
File.open("#{k}.txt", 'w'){|f| f.puts v}
end
这篇关于Ruby - 打印一个哈希到txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文