Good on you for learning Jenny
You need to assign your CSV.generate line to a variable, you can call
it "line" and then, each time you put something in line, you add it to
the end of an Array that we will call "file_lines". Then, once done,
you can just write the file_lines out to the file using puts instead
of write. This is becuase, with f.puts Ruby will put a return at the
end of each "line" of the "file_lines" array.
Something like:
···
================
# We have to initialize the array in this case
file_lines = Array.new
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
line = 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})"])
# Here is where we put the new line on the end of the array
file_lines.push(line)
i = i + 1
end
# The only change here is "puts" not "write"
filename = 'results.csv'
File.open filename, 'w+' do |f|
f.puts file_lines
end
======================
There are faster ways to do it that I am sure you will get other
emails from. But this one takes the least amount of modification to
your own code... try this, get it working, then try some of the more
advanced examples people will give you.
Regards
Mikel
On 7/25/07, Jenny Purcell <dontspamme@spam.com> wrote:
I'm reading Learn To Program, which is based around Ruby code, and it
has directions on how to write to a named file.
It looks like following these directions, I want to do something like
this, where "string" is the text I want to write to the file.filename = 'results.csv'
File.open filename, 'w' do |f|
f.write stringHowver, what I can't sort out is how exactly I get the string to write
to the file.Here's the code I use now:
# 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
endThen, 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?Jenny