Ruby - Printing a hash to txt file [closed]

2019-08-29 16:23发布

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?

标签: ruby hash
4条回答
叼着烟拽天下
2楼-- · 2019-08-29 16:54
hash.each do |key,value|

File.open("nameoffile.txt", "w"){ |file| file.puts value} #Opened file gets each value of correposnding hash key's

end

or just

hash.each_value do |value|

File.open("nameoffile.txt", "w"){ |file| file.puts value} #Opened file gets each value of correposnding hash key's

end
查看更多
唯我独甜
3楼-- · 2019-08-29 17:02

Try something like:

hash.each do |key, vals|
  File.open("#{key}.txt", 'w') { |file| file.puts *vals }
end
查看更多
贼婆χ
4楼-- · 2019-08-29 17:04

I'd use File.write:

hash = { 'a' => [ 'abc' , 'def', 'ghi'] , 'b' => [ 'jkl' , 'mno' , 'pqr' ] }
hash.each { |k, v| File.write(k, v.join("\n")) }

Or:

hash.each { |k, v| File.write(k, v * "\n") }

If you want a carriage return at the end of the final line, then one of the answers using puts in a loop will work. Some applications care whether there is a trailing line-ending, others don't.

查看更多
做自己的国王
5楼-- · 2019-08-29 17:05
hash = { 'a' => [ 'abc' , 'def', 'ghi'] , 'b' => [ 'jkl' , 'mno' , 'pqr' ] }
hash.each do |k,v|
  File.open("#{k}.txt", 'w'){|f| f.puts v}
end
查看更多
登录 后发表回答