在Ruby中创建一个空文件:"触摸"等效?

Abh*_*ert 112 ruby file

在Ruby中创建文件的最佳方法是什么?

类似于Unix命令,触摸:

touch file.txt
Run Code Online (Sandbox Code Playgroud)

Dav*_*ton 174

FileUtils.touch看起来像它做什么,和镜子*touch命令:

require 'fileutils'
FileUtils.touch('file.txt')
Run Code Online (Sandbox Code Playgroud)

*与触摸(1)不同,您无法单独更新mtime或atime.它也缺少一些其他不错的选择.


Mic*_*ohl 43

如果您担心文件句柄:

File.open("foo.txt", "w") {}
Run Code Online (Sandbox Code Playgroud)

来自文档:

如果给出了可选的代码块,它将作为参数传递打开的文件,并且当块终止时,File对象将自动关闭.

  • 值得指出的是,这实际上并不反映"触摸" - 如果文件存在,它将覆盖文件. (12认同)
  • 使用追加模式,如果文件已经存在,文件将不会被截断File.open("foo.txt","a"){}这也不会反映'touch',但是'touch(1)'不是这个问题. (3认同)

Mar*_*une 21

在Ruby 1.9.3+中,您可以使用File.write(aka IO.write):

File.write("foo.txt", "")
Run Code Online (Sandbox Code Playgroud)

对于早期版本,使用require "backports/1.9.3/file/write"或使用File.open("foo.txt", "w") {}