Reputation: 283
Consider the following code:
(1..10).each do |i|
thing1 = i
aFile = File.new("input.txt", "r+")
if aFile
aFile.syswrite(thing1)
else
puts "Unable to open file!"
end
end
I am trying to print every value of i (in this case 1,2,3,...,10) into the file separated by a line:
1
2
3
...
9
10
How do I do that, knowing that the following code only saves the latest output ("10").
Thanks!
Upvotes: 1
Views: 165
Reputation: 84343
How do I do that, knowing that the following code only saves the latest output ("10").
Don't do that. Use File#puts instead.
File.open('file', 'w') do |f|
(1..10).each { |i| f.puts i }
end
Note that the above can be written faster and much more compactly as:
File.open('file', 'w') { |f| f.puts (1..10).to_a }
by writing the array to the file with a single method call to #puts, rather than writing once per iteration. The results in the file remain the same, though.
Upvotes: 2