如何简洁地将文本附加到文件中

时间:2021-10-12 03:06:06

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

2 个解决方案

#1


7  

This has been answered in great depth already:

这已经得到了很好的回答:

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

你可以在Ruby中一行创建/写/附加一个字符串

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

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

#2


6  

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

#1


7  

This has been answered in great depth already:

这已经得到了很好的回答:

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

你可以在Ruby中一行创建/写/附加一个字符串

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

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

#2


6  

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