Is it possible to do this?
v='some text'
w='my' + Time.new.strftime("%m-%d-%Y").to_s + '.txt'
File.write(w,v) # will create file if it doesn't exist and recreates everytime
without having to do File.open on an instance? Ie just a class method that will either append or create and write? Ideally a ruby 1.9.3 soln.
thx
Edit 1
here's what I tried based upon docs. I hadn't seen the rdoc but had seen some other examples. Again I'm just asking if possible to open a file in append mode via File.write? thx
irb(main):014:0> File.write('some-file.txt','here is some text',"a")
TypeError: can't convert String into Integer
from (irb):14:in `write'
from (irb):14
from /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/irb:13:in `<main>'
irb(main):015:0>
irb(main):015:0> File.write('some-file.txt','here is some text',O_APPEND)
NameError: uninitialized constant O_APPEND
from (irb):15
from /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/irb:13:in `<main>'
irb(main):016:0>
You can use the + operator to append a string to another. In this case, a + b + c , creates a new string. Btw, you don't need to use variables to make this work.
"\n" is newline, '\n\ is literally backslash and n.
Solution: Appending text to a file with Ruby is similar to other languages: you open the file in "append" mode, write your data, and then close the file. Here's a quick example that demonstrates how to append "Hello, world" to a file named myfile. out in the current directory: open('myfile.
Here is the another example of opening a file in Ruby. fileObject = File. open("tutorials. txt","r"); print(fileObject.
Ruby has had IO::write
since 1.9.3. Your edit shows you're passing the wrong args. The first arg is a filename, the second the string to write, the third is an optional offset, and the fourth is a hash that can contain options to pass to the open. Since you want to append, you'll need to pass the offset as the current size of the file to use this method:
File.write('some-file.txt', 'here is some text', File.size('some-file.txt'), mode: 'a')
Hoisting from the discussion thread:
This method has concurrency issues for append because the calculation of the offset is inherently racy. This code will first find the size is X, open the file, seek to X and write. If another process or thread writes to the end between the File.size
and the seek/write inside File::write
, we will no longer be appending and will be overwriting data.
If one opens the file using the 'a' mode and does not seek, one is guaranteed to write to the end from the POSIX semantics defined for fopen(3) with O_APPEND
; so I recommend this instead:
File.open('some-file.txt', 'a') { |f| f.write('here is some text') }
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