【问题标题】:What is the best way to write to a file in Ruby? [closed]在 Ruby 中写入文件的最佳方法是什么? [关闭]
【发布时间】:2008-09-29 21:19:34
【问题描述】:

我想用 Ruby 将一些数据写入文件。最好的方法是什么?

【问题讨论】:

    标签: ruby file-io


    【解决方案1】:
    File.open("a_file", "w") do |f|
        f.write "some data"
    end
    

    您也可以根据个人口味/需要使用f << "some data"f.puts "some data" 来换行。如果您想追加到文件而不是在每次打开时截断,请将 "w" 更改为 "a"

    【讨论】:

    • 我同意将块传递给 File.open。这是最安全的方法,因为无论那里发生什么(正确执行、异常等),都可以保证正确关闭文件。
    【解决方案2】:
    require 'rio'
    rio('foo.txt') < 'bar'
    

    http://rio.rubyforge.org/

    【讨论】:

      【解决方案3】:

      除了File.newFile.open(以及所有其他有趣的 IO 内容)之外,您可能希望,特别是如果您正在从 Ruby 中保存并加载回 Ruby 并且您的数据在对象中,则可以使用 Marshal 查看直接保存和加载您的对象。

      【讨论】:

        【解决方案4】:

        使用 File::open 是最好的方法:

        File.open("/path/to/file", "w") do |file|
          file.puts "Hello file!"
        end
        

        如前所述,您可以使用“a”而不是“w”来追加文件。可能还有其他可用的模式,在ri IORuby Quickref 下列出。

        【讨论】:

          【解决方案5】:
          filey = File.new("/path/to/the/file", APPEND)
          filey.puts "stuff to write"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-07-30
            • 2020-09-01
            • 1970-01-01
            • 2010-09-08
            • 2020-12-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多