From: 7stud -- Date: 2009-02-14T01:08:07+09:00 Subject: Re: help reading data from a file Zoe Phoenix wrote: > > One problem I'm facing is how to read an array from a file. If I have a > file with only an array in it, how do I apply a method such as > ".generate" to the array? > arr = %w{Nashville Orlando Tampa Memphis} File.open("data.txt", "w") do |f| Marshal.dump(arr, f) end cities = nil File.open("data.txt") do |f| cities = Marshal.load(f) end p cities p cities.length p cities.reverse --output:-- ["Nashville", "Orlando", "Tampa", "Memphis"] 4 ["Memphis", "Tampa", "Orlando", "Nashville"] > > cities = ['Nashville', > 'Orlando', > 'Tampa' > 'Memphis' > ] > > cities.each do |city| > output = %Q(#{city}) > dir = "/some/path/#{city.downcase.delete(' ')}.txt" > > File::open(dir, 'w') do |f| > f.write output > end > end > > I have a ruby program that I use to generate text files from a single > array's data, but what I would like to do is be able to have it generate > files from multiple arrays and save them in a different folder when it > starts writing files from a different array. > data = { 'cities' => %w{Nasheville Olrando Tampa Memphis}, 'dogs' => %w{small medium large}, 'friends' => %w{Dave Cathy Jill} } dirs = { 'cities' => './a', #Must be existing dirs 'dogs' => './b', 'friends' => './c' } data.each do |key, val| current_path = "#{dirs[key]}/#{key}" File.open(current_path, "w") do |f| val.each do |arr_element| f.write "#{arr_element} " end end end -- Posted via http://www.ruby-forum.com/.