user3610137
user3610137

Reputation: 283

Ruby - printing a "loop" to file

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

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Use File#puts

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

Writing an Array Instead of Looping

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

Related Questions