How to create a file in Ruby

后端 未结 9 1227
再見小時候
再見小時候 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:43
    data = 'data you want inside the file'.
    

    You can use File.write('name of file here', data)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 18:47

    OK, now I feel stupid. The first two definitely do not work but the second two do. Not sure how I convinced my self that I had tried them. Sorry for wasting everyone's time.

    In case this helps anyone else, this can occur when you are trying to make a new file in a directory that does not exist.

    0 讨论(0)
  • 2020-11-28 18:47

    You can also use constants instead of strings to specify the mode you want. The benefit is if you make a typo in a constant name, your program will raise an runtime exception.

    The constants are File::RDONLY or File::WRONLY or File::CREAT. You can also combine them if you like.

    Full description of file open modes on ruby-doc.org

    0 讨论(0)
  • 2020-11-28 18:52

    Try

    File.open("out.txt", "w") do |f|     
      f.write(data_you_want_to_write)   
    end
    

    without using the

    File.new "out.txt"
    
    0 讨论(0)
  • 2020-11-28 18:58

    Try using "w+" as the write mode instead of just "w":

    File.open("out.txt", "w+") { |file| file.write("boo!") }
    
    0 讨论(0)
提交回复
热议问题