# Write to file

**URL:** <https://www.ruby-forum.com/t/write-to-file/193417>\
**Category:** Ruby\
**Created:** [August 17, 2010, 12:46pm UTC](https://www.ruby-forum.com/t/write-to-file/193417 "2010-08-17T12:46:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![taura](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9f8e36/32.png) [@taura](https://www.ruby-forum.com/u/taura)\
**Post date:** [August 17, 2010, 12:46pm UTC](https://www.ruby-forum.com/t/write-to-file/193417/1 "2010-08-17T12:46:18Z")

</div>

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:in`new’  
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

---

<div class="post-metadata">

**Author:** ![taura](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9f8e36/32.png) [@taura](https://www.ruby-forum.com/u/taura)\
**Post date:** [August 17, 2010, 12:53pm UTC](https://www.ruby-forum.com/t/write-to-file/193417/2 "2010-08-17T12:53:07Z")

</div>

On Tue, Aug 17, 2010 at 12:46 PM, T. A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> like this:
> 
> …\rubyfile.rb:116:in `initialize': Invalid argument - test (Errno::EINVAL) .txt from ..\rubyfile.rb:116:in `new’  
> 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.

---

<div class="post-metadata">

**Author:** ![taura](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9f8e36/32.png) [@taura](https://www.ruby-forum.com/u/taura)\
**Post date:** [August 17, 2010, 12:59pm UTC](https://www.ruby-forum.com/t/write-to-file/193417/3 "2010-08-17T12:59:29Z")

</div>

Hey, thanks very much, its working!

taura
