Search code examples
rubyfileioerrno

How to create a file in Ruby


I'm trying to create a new file and things don't seem to be working as I expect them to. Here's what I've tried:

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

According to everything I've read online all of those should work but every single one of them gives me this:

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

This happens from IRB as well as a Ruby script. What am I missing?


Solution

  • Use:

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

    where your options are:

    • r - Read only. The file must exist.
    • w - Create an empty file for writing.
    • a - Append to a file.The file is created if it does not exist.
    • r+ - Open a file for update both reading and writing. The file must exist.
    • w+ - Create an empty file for both reading and writing.
    • a+ - Open a file for reading and appending. The file is created if it does not exist.

    In your case, 'w' is preferable.

    OR you could have:

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

    ... but that has the risk of forgetting to call close (such as if an exception is raised, or you return early).