Search code examples
rubyfiledir

How to write a file in specific path in ruby


I want to save my files in specific path.. I have used like this

file_name = gets 
F = open.(Dir.pwd, /data/folder /#{@file_name },w+)

I'm not sure whether the above line is correct or not! Where Dir.pwd tell the directory path followed by my folder path and the file name given.

It should get store the value on the specific path with the specific file name given. Can anyone tell me how to do that.


Solution

  • Your code has multiple errors. Have you ever tried to execute the script?

    Your script ends with:

    test.rb:7: unknown regexp options - fldr
    test.rb:7: syntax error, unexpected end-of-input
        F = open.(Dir.pwd, /data/folder /#{@file_name },w+)
    

    First: You need to define the strings with ' or ":

    file_name = gets 
    F = open.(Dir.pwd, "/data/folder/#{@file_name}","w+")
    

    Some other errors:

    • You use file_name and later @file_name.
    • The open method belongs to File and needs two parameters.
    • The file is defined as a constant F. I would use a variable.
    • The path must be concatenated. I'd use File.join for it.
    • You don't close the file.

    After all these changes you get:

    file_name = gets
    f = File.open(File.join(Dir.pwd, "/data/folder/#{file_name}"),"w+")
    ##
    f.close
    

    and the error:

      test.rb:29:in `initialize': No such file or directory @ rb_sysopen - C:/Temp/data/folder/sdssd (Errno::ENOENT)
    

    The folder must exist, so you must create it first.

    Now the script looks like:

    require 'fileutils'
    dirname = "data/folder"
    file_name = gets.strip
    FileUtils.mkdir_p(dirname) unless Dir.exists?(dirname)
    f = File.open(File.join(Dir.pwd, dirname, file_name),"w+")
    ##fill the content
    f.close