简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM