Ruby - Printing a hash to txt file [closed]

2019-08-29 16:43发布

问题:

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?

回答1:

hash = { 'a' => [ 'abc' , 'def', 'ghi'] , 'b' => [ 'jkl' , 'mno' , 'pqr' ] }
hash.each do |k,v|
  File.open("#{k}.txt", 'w'){|f| f.puts v}
end


回答2:

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.



回答3:

Try something like:

hash.each do |key, vals|
  File.open("#{key}.txt", 'w') { |file| file.puts *vals }
end


回答4:

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


标签: ruby hash