Write to file

Hi,

I’m trying to write to a new file, wich I’m creating by

file=File.new(‘file.txt’, ‘w’)

This works fine so far, the file is created in my working folder and
contains the text I’m putting in.

Now I want the user to input the filename, so I modified my source code
like this:

print "Please insert file name: "

file_name=gets

file=File.new(file_name+’.txt’, ‘w’)

Running the Programm and inputting ‘test’ (without the ‘’), I get the
following Error:

…\rubyfile.rb:116:in initialize': Invalid argument - test (Errno::EINVAL) .txt from ..\rubyfile.rb:116:innew’
from …\rubyfile.rb:116

I have no idea, what’s going wrong… Since file_name is a string,
file_name+’.txt’ ought to be a string too, and thus a valid argument for
the initializer method of File, or not?

Sorry, if my question is dumb, I’m a total noob with ruby…

Thanks for any help!

taura

On Tue, Aug 17, 2010 at 12:46 PM, T. A. [email protected] wrote:

like this:

…\rubyfile.rb:116:in initialize': Invalid argument - test (Errno::EINVAL) .txt from ..\rubyfile.rb:116:innew’
from …\rubyfile.rb:116

The problem is that gets returns the \n at the end of the string, so
file_name + “.txt” is “test\n.txt”, which seems to be an invalid
filename. Try this:

file_name = gets.chomp

I have no idea, what’s going wrong… Since file_name is a string,
file_name+’.txt’ ought to be a string too, and thus a valid argument for
the initializer method of File, or not?

BTW, use the block form of File.open, it ensures that the file is
closed:

File.open("#{file_name}.txt", “w”) do |file|

end

Jesus.

Hey, thanks very much, its working!

taura

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs