How to create a file in Ruby

后端 未结 9 1329
再見小時候
再見小時候 2020-11-28 18:04

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

File.new \"out.txt\"
File.open \"out.tx         


        
9条回答
  •  天命终不由人
    2020-11-28 18:46

    Use:

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

    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
    

提交回复
热议问题