What's the difference between Ruby's puts and write methods?

前端 未结 2 1903
执念已碎
执念已碎 2021-02-18 18:32

What\'s the difference between...

File.open(\'abc\', \'w\') { |f| f.puts \'abcde\' }

...and...

File.open(\'abc\', \'w\') { |f|          


        
相关标签:
2条回答
  • 2021-02-18 19:02

    puts appends a newline, write does not. Technically, puts appends the record separator (which is usually a newline) to the output if it doesn't have one at the end. write outputs only what it is given.

    0 讨论(0)
  • 2021-02-18 19:05

    In cases like this, I always start with the Ruby Core documentation, in this case the IO class.

    ios.puts(obj, ...) => nil
    

    Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

    ios.write(string) => integer
    

    Writes the given string to ios. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written.

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