简体   繁体   English

Ruby 的 puts 和 write 方法有什么区别?

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

What's the difference between...有什么区别...

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

...and... ...和...

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

...? ...?

puts appends a newline, write does not. puts 附加一个换行符, write 没有。 Technically, puts appends the record separator (which is usually a newline) to the output if it doesn't have one at the end.从技术上讲, puts 将记录分隔符(通常是换行符)附加到 output 如果它最后没有一个。 write outputs only what it is given. write 只输出给定的内容。

In cases like this, I always start with the Ruby Core documentation, in this case the IO class.在这种情况下,我总是从 Ruby 核心文档开始,在这种情况下是IO class。

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

Writes the given objects to ios as with IO#print .将给定对象写入 ios 与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.如果在没有 arguments 的情况下调用,则输出单个记录分隔符。

ios.write(string) => integer

Writes the given string to ios.将给定的字符串写入 ios。 The stream must be opened for writing. stream 必须打开才能写入。 If the argument is not a string, it will be converted to a string using to_s .如果参数不是字符串,它将使用to_s转换为字符串。 Returns the number of bytes written.返回写入的字节数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM