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:

    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).