在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对象将自动关闭.
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") {}