ruby - 如何增加写入ruby文件的计数器

标签 ruby file

我正在计算模块在文件中失败的次数。所以每当它失败时,我都会打开文件,增加文件中的数字并关闭它。我怎样才能做到这一点,只打开文件一次,而不是打开文件两次,一次用于读取,另一次用于写入。

谢谢

最佳答案

假定一个名为 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/

相关文章:

javascript - Stripe 形式不创建 token

ruby - irb 无权访问我的模型(NameError : uninitialized constant)

java - 如何将数组中的某些 File 元素复制到新的 File 数组?

java - 如何使 Java Process Builder 将输出 append 到输出文件?

c++ - 在删除文件之前检查文件是否仍在被另一个进程使用(c、c++、linux)

ruby - 将时间与毫秒进行比较

ruby - 用空项替换数组中的每一项

ruby-on-rails - 列出目录中具有不同扩展名的文件

java - 检查数组索引中的数据

c# - 搜索 1GB CSV 文件