From: Todd Benson Date: 2007-07-25T14:56:45+09:00 Subject: Re: Newbie question, writing to a file On 7/24/07, Jenny Purcell wrote: > # Print out results to csv file line by line > while i <= count do > j = number.detect {|c| position[c - 1] == i + 1} > j = j - 1 > # Push each horse's name, owner, score, pre_points, dice rolls, > and other info into a new csv file > puts CSV.generate_line(["pp#{pole_new[j]}", horse_name[j], > horse_info[j], owners_initials[j], best_result[j], race_style[j], > best_time[j], pre_points[j], roll_1[j], roll_2[j], roll_3[j], > roll_4[j], roll_5[j], score[j], "#{position[j]}(#{count + 1})"]) > i = i + 1 > end > > Then, what I do is run the program and use 'racing.rb > results.csv' > to actually write to a results file. I'd like the next step to be that > it writes to its own results file without me having to name it each > time I run the program. > > How do I set up the CSV lines that I generate to be put in a string > (or object) that I can then send to a file? Here's one way to do it... File.open('results.csv' , 'w') do |file| 1.upto 5 do |idx| file.puts(CSV.generate_line(["a", "b", "c", idx]) end end which is probably better than the way I usually do it by throwing the String together first... str_to_write = "" 1.upto 5 do |idx| str << CSV.generate_line(["a", "b", "c", idx]) << "\n" end File.open('results.csv', 'w') { |file| file.write str_to_write } Todd