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
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.
Try something like:
hash.each do |key, vals|
File.open("#{key}.txt", 'w') { |file| file.puts *vals }
end
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