How to create a file in Ruby

后端 未结 9 1228
再見小時候
再見小時候 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:58

    The directory doesn't exist. Make sure it exists as open won't create those dirs for you.

    I ran into this myself a while back.

    0 讨论(0)
  • 2020-11-28 19:03

    If the objective is just to create a file, the most direct way I see is:

     FileUtils.touch "foobar.txt"
    
    0 讨论(0)
  • 2020-11-28 19:10

    File.new and File.open default to read mode ('r') as a safety mechanism, to avoid possibly overwriting a file. We have to explicitly tell Ruby to use write mode ('w' is the most common way) if we're going to output to the file.

    If the text to be output is a string, rather than write:

    File.open('foo.txt', 'w') { |fo| fo.puts "bar" }
    

    or worse:

    fo = File.open('foo.txt', 'w')
    fo.puts "bar"
    fo.close
    

    Use the more succinct write:

    File.write('foo.txt', 'bar')
    

    write has modes allowed so we can use 'w', 'a', 'r+' if necessary.

    open with a block is useful if you have to compute the output in an iterative loop and want to leave the file open as you do so. write is useful if you are going to output the content in one blast then close the file.

    See the documentation for more information.

    0 讨论(0)
提交回复
热议问题