简体   繁体   English

Ruby-打印“循环”到文件

[英]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: 我正在尝试将i的每个值(在本例中为1,2,3,...,10)打印到由一行分隔的文件中:

1
2
3
...
9
10

How do I do that, knowing that the following code only saves the latest output ("10"). 我该怎么做,知道以下代码仅保存最新的输出(“ 10”)。

Thanks! 谢谢!

Use File#puts 使用文件#puts

How do I do that, knowing that the following code only saves the latest output ("10"). 我该怎么做,知道以下代码仅保存最新的输出(“ 10”)。

Don't do that. 不要那样做 Use File#puts instead. 请改用File#puts

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. 通过对#puts的单个方法调用将数组写入文件,而不是每次迭代写入一次。 The results in the file remain the same, though. 但是,文件中的结果保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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