Read, edit, and write a text file line-wise using Ruby

后端 未结 4 611
长情又很酷
长情又很酷 2020-12-02 11:06

Is there a good way to read, edit, and write files in place in Ruby?

In my online search I\'ve found stuff suggesting to read it all into an array, modify said array

4条回答
  •  渐次进展
    2020-12-02 11:40

    Just in case you are using Rails or Facets, or you otherwise depend on Rails' ActiveSupport, you can use the atomic_write extension to File:

    File.atomic_write('path/file') do |file|
      file.write('your content')
    end
    

    Behind the scenes, this will create a temporary file which it will later move to the desired path, taking care of closing the file for you.

    It further clones the file permissions of the existing file or, if there isn't one, of the current directory.

提交回复
热议问题