你能在 Ruby 的一行中创建/写入/附加一个字符串到文件吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15865140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:52:12  来源:igfitidea点击:

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

ruby

提问by timpone

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.

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

thx

谢谢

Edit 1

编辑 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

这是我根据文档尝试的方法。我没有看过 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>

回答by dbenhur

Ruby has had IO::writesince 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:

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

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.sizeand the seek/write inside File::write, we will no longer be appending and will be overwriting data.

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

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:

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

File.open('some-file.txt', 'a') { |f| f.write('here is some text') }

回答by akostadinov

To make it clear as some comments are suggesting I tested this working: IO.write("/tmp/testfile", "gagaga\n", mode: 'a')

为了明确一些评论建议我测试了这个工作: IO.write("/tmp/testfile", "gagaga\n", mode: 'a')

That one appends to the file without need to calculate offset. Rubydoc is little misleading. Here's a bug about that: https://bugs.ruby-lang.org/issues/11638

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

回答by ennuikiller

File.open('my' + Time.new.strftime("%m-%d-%Y").to_s + '.txt', 'w') { |file| file.write("some text") }

回答by Joshua Cheek

MRI has that method already (I literally copied and pasted your code and it worked), but last time I checked, JRuby and Rubinius didn't. They might now, I don't feel like installing the latest versions to see.

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

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

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