例如,在我写的这行代码中,print和put会产生不同的结果。

1.upto(1000).each { |i| print i if i % 2 == 0 }

当前回答

Print输出每个参数,后跟$,,到$stdout,后跟$\。它等价于args.join($,) + $\

将$和$\设置为"\n",然后执行与print相同的操作。关键的区别在于,每个参数都是包含看跌期权的新行。

你可以要求“english”来访问那些具有用户友好名称的全局变量。

其他回答

Print输出每个参数,后跟$,,到$stdout,后跟$\。它等价于args.join($,) + $\

将$和$\设置为"\n",然后执行与print相同的操作。关键的区别在于,每个参数都是包含看跌期权的新行。

你可以要求“english”来访问那些具有用户友好名称的全局变量。

Puts调用每个参数的to_s,并向每个字符串添加一个新行,如果它不以new line结束。 Print只是通过调用它们的to_s来输出每个参数。

例如: 写上“一二”: 一个两个

{新行}

输入“一二\n”: 一个两个

{new line} #put不会向结果中添加新行,因为字符串以新行结束

打印“一二”: 一个两个

打印“一二\n”: 一个两个

{新行}

还有另一种输出方式:p

对于每个对象,直接写入obj。Inspect后面跟着一个换行符指向程序的标准输出。

有助于输出调试信息。 P "aa\n\t": aa\n\t

如果你想使用puts在字符串中输出数组,你将得到与使用print相同的结果:

puts "#{[0, 1, nil]}":
[0, 1, nil]

但如果不是在一个带引号的字符串中,那么是。唯一的区别是当我们使用看跌期权时,换行。

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

print() → nil print(obj, ...) → nil Writes the given object(s) to ios. Returns nil. The stream must be opened for writing. Each given object that isn't a string will be converted by calling its to_s method. When called without arguments, prints the contents of $_. If the output field separator ($,) is not nil, it is inserted between objects. If the output record separator ($\) is not nil, it is appended to the output. ... puts(obj, ...) → nil Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns nil. The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its to_s method. If called without arguments, outputs a single newline.

对上面给出的点做了一点实验,区别似乎是:

Called with multiple arguments, print separates them by the 'output field separator' $, (which defaults to nothing) while puts separates them by newlines. puts also puts a newline after the final argument, while print does not. 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 puts automatically unpacks arrays, while print does not: 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 with no arguments prints $_ (the last thing read by gets), while puts prints a newline: 2.1.3 :001 > gets hello world => "hello world\n" 2.1.3 :002 > puts => nil 2.1.3 :003 > print hello world => nil print writes the output record separator $\ after whatever it prints, while puts ignores this variable: 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

如果已经没有参数,则Puts在每个参数的末尾添加新行。

打印不会添加新行。


例如:

put [[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输出。