How to create a file in Ruby

I am trying to create a new file, but things don’t seem to work as I expected. Here is what I tried:

File.new "out.txt"
File.open "out.txt"
File.new "out.txt","w"
File.open "out .txt","w"

According to everything I read online, all of these should work but each one gives me this:

 ERRNO::ENOENT: No such file or directory-out.txt

This happens in IRB and ruby ​​files. What am I missing?

Use:

File .open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

Your choice is:

< p>> r – read only. The file must exist.
> w – create an empty file for writing.
> a – append to the file. If the file does not exist, create the file.
> r – Open the file for reading and writing updates. The file must exist.
> w – Create an empty file for reading and writing.
> a – Open the file for reading and appending. If If the file does not exist, create the file.

In your case,’w’ is more preferable.

Or you can:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

I am trying to create a new file, but things don’t seem to work as I expected. Here is what I tried: < p>

File.new "out.txt"
File.open "out.txt"
File.new "out.txt"," w"
File.open "out.txt","w"

Based on everything I read online, all of these should work but each one gives me this:

ERRNO::ENOENT: No such file or directory-out.txt

This happens in IRB and ruby ​​files. What am I missing?

Use:

File.open("out.txt", [your- option-string]) {|f| f.write("write your stuff here") }

Your choice is:

> r-read only. The file must exist .
> w – create an empty file for writing.
> a – append to the file. If the file does not exist, create the file.
> r – open the file for reading and writing Update. The file must exist.
> w – Create an empty file for reading and writing.
> a – Open the file for reading and appending. If the file does not exist, create the file.

In your case,’w’ is preferable.

Or you can:

out_file = File.new("out. txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

< /p>

Leave a Comment

Your email address will not be published.