'How do I print multiple lines in Ruby to text file, without overwriting the older text
I'm building a small application with discordrb that logs Discord messages to a .txt file.
@bot.message do |event|
begin
loggies = event.content, event.author, event.timestamp, event.channel.name
File.open("loggies.txt", "w") do |f|
f << "#{loggies}\n"
end
rescue
puts "rescued"
end
end
@bot.run
Ive tried many ways to put f into the file.open, puts print etc. This is my most recent attempt. No matter what I try I cant just get a log of multiple different entries.
Solution 1:[1]
When you open the file with 'w' mode all existing content will be deleted. Use 'a' (append) instead of 'w':
File.open("loggies.txt", "a") do |f|
f << "#{loggies}\n"
or easier:
File.write("loggies.txt", "#{loggies}\n", mode: "a")
Here you can find list of available modes: https://ruby-doc.org/core-2.5.1/IO.html#method-c-new
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leon |
