Abhi Beckert
Abhi Beckert

Reputation: 33369

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

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

Something similar to the Unix command, touch:

touch file.txt

Upvotes: 141

Views: 51945

Answers (5)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

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") {}

Upvotes: 30

Dave Newton
Dave Newton

Reputation: 160211

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.

Upvotes: 207

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

And also, less advantageous, but very brief:

`touch file.txt`

Upvotes: 4

Michael Kohl
Michael Kohl

Reputation: 66837

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.

Upvotes: 52

WarHog
WarHog

Reputation: 8710

Just an example:

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

Upvotes: -2

Related Questions