How to Create a New File

S

Skeets

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...
 
H

Harold Hausman

How about something like this:

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

#hth,
# -Harold
 
N

N Okia

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")
 
M

Morton Goldberg

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
 
S

Skeets

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.
 
S

Skeets

Skeets said:
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.
 
C

Chad Perrin

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.
 
H

Hal Fulton

Skeets said:
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. :)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,209
Messages
2,571,088
Members
47,684
Latest member
sparada

Latest Threads

Top