16

是否有可能做到这一点?

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 

无需在实例上执行 File.open?即只是一个将追加或创建和写入的类方法?理想情况下是红宝石 1.9.3 溶液。

谢谢

编辑 1

这是我根据文档尝试过的。我没有看过 rdoc,但看过其他一些例子。我再次询问是否可以通过 File.write 以附加模式打开文件?谢谢

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>
4

4 回答 4

49

RubyIO::write从 1.9.3 开始就有了。您的编辑显示您传递了错误的参数。第一个 arg 是文件名,第二个是要写入的字符串,第三个是可选的偏移量,第四个是一个散列,可以包含传递给 open 的选项。由于要追加,因此需要将偏移量作为文件的当前大小传递以使用此方法:

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

来自讨论线程的提升: 此方法对于 append 存在并发问题,因为偏移量的计算本质上是 racy。此代码将首先找到大小为 X,打开文件,寻找 X 并写入。File.size如果另一个进程或线程在和 seek/write inside之间写到末尾File::write,我们将不再追加并覆盖数据。

如果使用 'a' 模式打开文件并且不查找,则可以保证从为fopen(3) 定义的 POSIX 语义写入到末尾,其中O_APPEND; 所以我推荐这个:

File.open('some-file.txt', 'a') { |f| f.write('here is some text') }
于 2013-04-07T18:04:47.997 回答
12

为了清楚起见,一些评论表明我测试了这个工作: IO.write("/tmp/testfile", "gagaga\n", mode: 'a')

那个附加到文件而不需要计算偏移量。Rubydoc 几乎没有误导性。这是一个关于此的错误: https ://bugs.ruby-lang.org/issues/11638

于 2015-10-30T09:48:45.290 回答
4
File.open('my' + Time.new.strftime("%m-%d-%Y").to_s + '.txt', 'w') { |file| file.write("some text") }
于 2013-04-07T17:02:35.257 回答
3

MRI 已经有这种方法(我实际上是复制并粘贴了您的代码并且它有效),但上次我检查时,JRuby 和 Rubinius 没有。他们可能现在,我不想安装最新版本来查看。

http://rdoc.info/stdlib/core/IO.write

于 2013-04-07T17:11:32.997 回答