0

I have a file in which one I want to store some datas.

Using IRB, I can add different lines in the file. However, using a Ruby script writen in a file, I have issues.

I can write a line, it is stored as it should be, but when I re launch the script and re use the method, it overwrites what was in the file instead of adding content at the next line.

def create_new_account
    puts "Set the account's name"
    @account_name = gets
    puts "New account's name: #{@account_name}
    open("accounts.txt","w+") do |account_file|
        account_file.write "ac;#{@account_name}\n"

    end
end

I had a look to the different parameters of the method open, but seems like it's not there. Moreover, I tried puts instead of write, but there is no difference, always the same problem.

Could someone help me understand what is wrong with the code?

Thanks

Itération 122442
  • 2,644
  • 2
  • 27
  • 73
  • http://stackoverflow.com/questions/3682359/what-are-the-ruby-file-open-modes-and-options but as stated you need append – Doon Aug 08 '16 at 21:38

1 Answers1

0

Try opening the file in append mode like so

open('accounts.txt', 'a+')

otherwise the file is opened so as to overwrite the existing data.

"a" - Write-only, each write call appends data at end of file. Creates a new file for writing if file does not exist.

obataku
  • 29,212
  • 3
  • 44
  • 57