ceah
ceah

Reputation: 1

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.

Upvotes: 0

Views: 174

Answers (1)

Leon
Leon

Reputation: 146

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

Upvotes: 3

Related Questions