print和puts有什么区别?

258 ruby

例如,在这行代码我写的,print并puts产生不同的结果.

1.upto(1000).each { |i| print i if i % 2 == 0 }
Run Code Online (Sandbox Code Playgroud)

mik*_*son 370

puts 如果没有一个参数,则在每个参数的末尾添加一个新行.

print 不添加新行.


例如:

puts [[1,2,3], [4,5,nil]] 会回来:

1
2
3
4
5

而print [[1,2,3], [4,5,nil]] 将返回:

[[1,2,3], [4,5,nil]]
请注意puts如何输出nil值而print不会.

  • 实际上,每个参数后都有一个换行符.这是一个关键点,并且从Ruby文档中不清楚(因为该示例只有1个参数). (88认同)
  • @Fronker,这仍然只是一个论点.编译器连接相邻的字符串. (6认同)
  • 还有一件事......扩展数组类并覆盖to_s方法.在打印时,puts不会将新的to_s用于新类的对象 (3认同)

MBe*_*ley 61

一个很大的区别是,如果您正在显示数组.特别是那些有NIL的人.例如:

print [nil, 1, 2]
Run Code Online (Sandbox Code Playgroud)

给

[nil, 1, 2]
Run Code Online (Sandbox Code Playgroud)

但

puts [nil, 1, 2]
Run Code Online (Sandbox Code Playgroud)

给

1
2
Run Code Online (Sandbox Code Playgroud)

注意,没有出现零项(只是一个空行)和不同行上的每个项目.


wer*_*mon 41

print输出每个参数,然后是$,,to $stdout,然后是$\.它相当于args.join($,) + $\

puts同时设置$,并$\成"\n",然后做同样的事情print.关键的区别在于每个参数都是一个新行puts.

您可以require 'english'使用用户友好的名称访问这些全局变量.


Mar*_*ery 18

API文档提供了一些很好的提示:

print() ? nil

print(obj, ...) ? nil

将给定对象写入ios.必须打开流才能写入.如果输出字段separator(nil)不是nil,则将在每个对象之间插入.如果输出记录separator(to_s)不是nil,则它将附加到输出.如果没有给出参数,则打印$_.非字符串的对象将通过调用其$,方法进行转换.如果没有参数,则打印变量的内容nil.返回零.

...

$\

将给定的对象写入ios,如同nil.在没有以换行符结束的任何内容之后写入记录分隔符(通常是换行符).如果使用数组参数调用,则将每个元素写入新行.如果不带参数调用,则输出单个记录分隔符.

用上面给出的点进行一些实验,差异似乎是:

  • 使用多个参数调用时,puts(obj, ...) ? nil将它们用"输出字段分隔符" nil(默认为空)to_s分隔,同时用换行符分隔它们.print在最后一个参数之后也会添加换行符,而$,不是.

    2.1.3 :001 > print 'hello', 'world'
    helloworld => nil 
    2.1.3 :002 > puts 'hello', 'world'
    hello
    world
     => nil
    2.1.3 :003 > $, = 'fanodd'
     => "fanodd" 
    2.1.3 :004 > print 'hello', 'world'
    hellofanoddworld => nil 
    2.1.3 :005 > puts 'hello', 'world'
    hello
    world
     => nil
    Run Code Online (Sandbox Code Playgroud)
  • puts自动解包数组,而puts不是:

    2.1.3 :001 > print [1, [2, 3]], [4]
    [1, [2, 3]][4] => nil 
    2.1.3 :002 > puts [1, [2, 3]], [4]
    1
    2
    3
    4
     => nil
  • print没有参数打印puts(最后读取的内容print),同时print打印换行符:

    2.1.3 :001 > gets
    hello world
     => "hello world\n" 
    2.1.3 :002 > puts
    
     => nil 
    2.1.3 :003 > print
    hello world
     => nil
    Run Code Online (Sandbox Code Playgroud)
  • $_在输出的gets任何内容之后写入输出记录分隔符,同时puts忽略此变量:

    mark@lunchbox:~$ irb
    2.1.3 :001 > $\ = 'MOOOOOOO!'
     => "MOOOOOOO!" 
    2.1.3 :002 > puts "Oink! Baa! Cluck! "
    Oink! Baa! Cluck! 
     => nil 
    2.1.3 :003 > print "Oink! Baa! Cluck! "
    Oink! Baa! Cluck! MOOOOOOO! => nil
    Run Code Online (Sandbox Code Playgroud)