How to Create a New File

let’s say I want to create a new file named new_file.txt. how do i do
this in ruby? it would seem to be trivial, however, i’m going through
the pickaxe book and i can’t find anything that relates to this.

tia…

How about something like this:

File.open( ‘new_file.txt’, ‘w’ ) {|file| file.write( ‘yo’ )}

#hth,

-Harold

Different ways:

Easy pure ruby:

f = File.open(“new_file.txt”,“w”)
f.close

Or if you are on *nix/cygwin:

system(“touch new_file.txt”)

This is just golfing, and I should be ashamed of myself, but
something like …

`>~/new_file.txt`

… will do it on most Unix systems (including Mac OS X).

Regards, Morton

On Sun, Jul 30, 2006 at 03:31:30PM +0900, Morton G. wrote:

This is just golfing, and I should be ashamed of myself, but
something like …

>~/new_file.txt

Whee, CLI obfu. Well, something potentially useful for it, anyway.

thanks, everyone.

Harold’s solution works. i tried this before posting, but got an
error. i guess i mucked up the code, b/c it works fine now.

thanks again.

Skeets wrote:

let’s say I want to create a new file named new_file.txt. how do i do
this in ruby? it would seem to be trivial, however, i’m going through
the pickaxe book and i can’t find anything that relates to this.

tia…

i know why my initial attempt was mucked up…

f = File.open( ‘new_file.txt’, ‘w’ )

i tried to assign it to a variable - that’s a no no in this case.

Skeets wrote:

i know why my initial attempt was mucked up…

f = File.open( ‘new_file.txt’, ‘w’ )

i tried to assign it to a variable - that’s a no no in this case.

Um, no… that’s not a nono. :slight_smile:

What did this do for you?

Of course, properly you’d use File.new in that case,
and if you use File.open you’d use a block…

Hal