在 Ruby 中创建一个空文件:“touch”等效吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8100574/
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 04:29:02  来源:igfitidea点击:

Creating an empty file in Ruby: "touch" equivalent?

rubyfile

提问by Abhi Beckert

What is the best way to create an emptyfile in Ruby?

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

Something similar to the Unix command, touch:

类似于 Unix 命令的东西,touch

touch file.txt

回答by Dave Newton

FileUtils.touchlooks like what it does, and mirrors*the touchcommand:

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

require 'fileutils'
FileUtils.touch('file.txt')

* Unlike touch(1)you can't update mtime or atime alone. It's also missing a few other nice options.

* 与touch(1)不同,您不能单独更新 mtime 或 atime。它还缺少其他一些不错的选择。

回答by Michael Kohl

If you are worried about file handles:

如果您担心文件句柄:

File.open("foo.txt", "w") {}

From the docs:

文档

If the optional code block is given, it will be passed the opened file as an argument, and the File object will automatically be closed when the block terminates.

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

回答by Marc-André Lafortune

In Ruby 1.9.3+, you can use File.write(a.k.a IO.write):

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

File.write("foo.txt", "")

For earlier version, either require "backports/1.9.3/file/write"or use File.open("foo.txt", "w") {}

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

回答by Boris Stitnicky

And also, less advantageous, but very brief:

而且,不太有利,但非常简短:

`touch file.txt`

回答by WarHog

Just an example:

只是一个例子:

File.open "foo.txt", "w"