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

RubyFile

Ruby Problem Overview


What is the best way to create an empty file in Ruby?

Something similar to the Unix command, touch:

touch file.txt

Ruby Solutions


Solution 1 - Ruby

FileUtils.touch looks like what it does, and mirrors* the touch command:

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.

Solution 2 - Ruby

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.

Solution 3 - Ruby

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

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

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

Solution 4 - Ruby

And also, less advantageous, but very brief:

`touch file.txt`

Solution 5 - Ruby

Just an example:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhi BeckertView Question on Stackoverflow
Solution 1 - RubyDave NewtonView Answer on Stackoverflow
Solution 2 - RubyMichael KohlView Answer on Stackoverflow
Solution 3 - RubyMarc-André LafortuneView Answer on Stackoverflow
Solution 4 - RubyBoris StitnickyView Answer on Stackoverflow
Solution 5 - RubyWarHogView Answer on Stackoverflow