我正在计算模块在文件中失败的次数。所以每当它失败时,我都会打开文件,增加文件中的数字并关闭它。我怎样才能做到这一点,只打开文件一次,而不是打开文件两次,一次用于读取,另一次用于写入。
谢谢
最佳答案
假定一个名为 counter.txt 的文件位于与调用脚本相同的目录中。该文件除了其中的数字外,应该没有其他任何内容。
File.open 'counter.txt' , 'r+' do |file|
num = file.gets.to_i
file.rewind
file.puts num.next
end
基本上,它 opens the file reading and writing starting at the beginning of the file 的“counter.txt”它使用 open 的 block 形式,以确保文件在完成后关闭。它gets the number然后 converts it to an integer获取当前计数。它rewinds the file pointer以便它再次位于文件的开头(因为我们想覆盖旧数字) 然后 prints out to the file递增的数字。
关于ruby - 如何增加写入ruby文件的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3178074/