s-cho-m
s-cho-m

Reputation: 1027

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.

Upvotes: 1

Views: 7138

Answers (1)

Sudarshan Dhokale
Sudarshan Dhokale

Reputation: 206

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

Upvotes: 3

Related Questions