Reputation: 1027
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
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