append to a file in ruby

To append content to a file in Ruby, you can use the File.open method with the a (append) mode flag. Here's an example:

main.rb
File.open("filename.txt", "a") do |file|
  file.puts "This line will be appended to the end of the file."
end
110 chars
4 lines

In the example above, we open the file filename.txt in append mode ("a"), which means that any content we write to the file will be added to the end of the existing file content. We use the File.open method with a block to automatically close the file when we're done writing to it.

Inside the block, we call the puts method on the file object to write a new line of content to the file. Since we're using puts, Ruby will automatically add a newline character ("\n") to the end of our string, ensuring that each line is appended to a new line in the file.

If the specified file doesn't exist, Ruby will create it for us.

gistlibby LogSnag