Search code examples
ruby

How to append a text to file succinctly


Instead of writing

File.open("foo.txt", "w"){|f| f.write("foo")}

We can write it

File.write("foo.txt", "foo")

Is there simpler way to write this one?

File.open("foo.txt", "a"){|f| f.write("foo")}

Solution

  • Yes. It's poorly documented, but you can use:

    File.write('foo.txt', 'some text', mode: 'a+')