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")}
You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
Instantiate the BufferedWriter class. By passing the FileWriter object as an argument to its constructor. Write data to the file using the write() method.
Likewise, the text to be added is stored in the variable text . Then, inside a try-catch block we use Files ' write() method to append text to the existing file. The write() method takes the path of the given file, the text to the written, and how the file should be open for writing.
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')
f = File.open('foo.txt', 'a') f.write('foo') f.close
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With