简体   繁体   中英

How to append a new line write to a file with ruby?

My code is:

def write_to_file(line, my_file)
  File.open(my_file, 'a') do |file|
    p '-----loop number:' + line.id.to_s
    file.puts "#{line.id}"
  end
end

If I loop three times with this method, I can see:

-----loop number:1
-----loop number:2
-----loop number:3

But it can only write the last id into my_file. Even I tried:

file << "#{line.id}"
# or
file.write "#{line.id}\n"

The result was the same.

try this

def write_to_file(line, my_file)
  File.open(my_file, 'a') do |file|
     p '-----loop number:' + line.to_s
     file.puts "#{line}"
  end
end

[1,2,3,4].each do |line|
  write_to_file(line, my_file)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM