ironsand
ironsand

Reputation: 15141

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")}

Upvotes: 41

Views: 30473

Answers (5)

karns
karns

Reputation: 5847

This has been answered in great depth already:

can you create / write / append a string to a file in a single line in Ruby

File.write(
  'some-file.txt', 
  'here is some text', 
  File.size('some-file.txt'), 
  mode: 'a'
)

Upvotes: 28

Gerry C
Gerry C

Reputation: 626

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

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

Upvotes: 33

DannyB
DannyB

Reputation: 14776

Although this was answered with multiple options, I have always felt that if Ruby has File.write path, content, it should also have File.append path, content, especially since the existing append syntax is not very pleasant.

So, whenever I need to append, I usually add this extension:

class File
  class << self
    def append(path, content)
      File.open(path, "a") { |f| f << content }
    end
  end
end

# Now it feels intuitive:

File.write "note.txt", "hello\n"
File.append "note.txt", "world\n"

Upvotes: 3

Thai
Thai

Reputation: 11354

You can use << instead of .write:

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

Upvotes: 4

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

f = File.open('foo.txt', 'a')
f.write('foo')
f.close

Upvotes: 19

Related Questions