File.new error

K

Kai Vermehr

Hi Forum,

I'm trying to create a file but I'm getting an error and can't find the
problem:

-------------------------
aFile = File.new("rubytestfile")

puts "hello"

aFile.close
-------------------------

I get this error. I'm working on Mac OS X:

Errno::ENOENT: No such file or directory - rubytestfile

thanks for any help!
 
R

Robert Klemme

Timothy said:
Try

aFile = File.new("rubytestfile", "w")

If you don't specify the 2nd argument (the open mode) Ruby assumes you
want to open the file for reading only. If the file doesn't exist, you
can't read it.

And please use the block form from the start, i.e.

File.open("rubytestfile", "w") do |aFile|
aFile.puts "hello"
end

Btw, the original script wrote to stdout and not to the file.

Kind regards

robert
 
J

John Maclean

Could this method be extended to acept input from stdin? Something
similar to:-

def testwrite
File.open("testfile", "w") { |file| file.gets "test" }
end
testwrite

The intention is to read lines from stdnin and put them into the file...
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: File.new error"

|Could this method be extended to acept input from stdin? Something
|similar to:-
|
|def testwrite
| File.open("testfile", "w") { |file| file.gets "test" }
|end
|testwrite
|
|The intention is to read lines from stdnin and put them into the file...

require 'fileutils'

def testwrite
File.open("testfile", "w") {|file|
FileUtils.copy_stream(STDIN, file)
}
end
 

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,202
Messages
2,571,057
Members
47,661
Latest member
sxarexu

Latest Threads

Top