Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4

Appending to a file in Ruby instead of replacing it


The following ruby code is replacing the entire contents of the file. How can I just append to the end of the file and keep it's existing contents intact?

File.open("db/seeds.rb", "w") do |f|
    f.write "Blog::Engine.load_seed"
end

Solution

  • Use append mode ("a"):

    File.open("db/seeds.rb", "a") do |f|
    

    Here is a link to the docs, on the different modes you can specify when opening a file.