0

I have a text file with path name file, and some content string that I want to append to it. I want to do something close to

File.open(file, "a"){|io| io.puts(string)}

but if the original content of the file does not end with an endline character $/, I want to insert one before string. What is the most effective way to do this?

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

1
File.open(file, 'r+') do |f|
  unless (last = f.readlines[-1]) && last.end_with?($/)
    f.puts $/
  end

  f.puts string
end
pje
  • 21,801
  • 10
  • 54
  • 70
  • I though that an answer would look like this, but didn't have in mind of using the `r+` mode. – sawa Nov 04 '12 at 05:49
-2
File.open(file, "a"){ |io| 
   io.puts
   io.puts(string)
}
ceth
  • 44,198
  • 62
  • 180
  • 289