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

前端 未结 2 908
谎友^
谎友^ 2021-02-18 18:21

What\'s the difference between...

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

...and...

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


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-18 19:04

    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.

提交回复
热议问题