01.弄懂p、print和puts的区别
约定
为了让整个文章的内容紧凑且可读性更强,下面的排版将遵循一下原则:
-
对一段代码打印结果的注解,采用"#>>",如下:
puts "Hello world!" #>> Hello world!
-
对一段代码/函数的返回结果的注解,采用"#=>",如下:
puts "Hello world!" #=> nil
-
常规的文字注释,采用"#",如下:
puts "Hello world!" # The code is used to print hello world to stdout.
内容
-
p函数调用对象的inspect函数,将inspect函数返回的结果输出到stdout。
-
print函数调用对象的to_s函数,将to_s函数返回的结果输出到stdout。
-
puts函数调用对象的to_s函数,将to_s函数返回的结果输出到stdout,并且还会额外输出一个换行符。
以下是在irb中做的一个小实验的结果:
irb(main):001:0> class Test irb(main):002:1> def inspect() irb(main):003:2> "This is inspect function." irb(main):004:2> end irb(main):005:1> def to_s() irb(main):006:2> "This is to_s function." irb(main):007:2> end irb(main):008:1> end => :to_s irb(main):009:0> t = Test.new() => This is inspect function. irb(main):010:0> p t This is inspect function. => This is inspect function. irb(main):011:0> print t This is to_s function.=> nil irb(main):012:0> puts t This is to_s function. => nil
-
使用"$, $\ $_"自定义print函数的输出
games = ["1", "2", "3"] $, = "|user-defined-sep|" # $,变量控制print函数中有多个参数需要打印时,参数之间的分隔符 $\ = "(user-defined-line-break)\n" # $\变量控制print函数的每次调用结束后需要追加打印的符号,一般用于设置换行符号 $_ ="*Be printed when nothing is given to print func*" # $_变量控制print函数在没有任何参数输入时的打印内容 print #=> *Be printed when nothing is given to print func*(user-defined-line-break) print games, games #=> ["1", "2", "3"]|user-defined-sep|["1", "2", "3"](user-defined-line-break) print games, games #=> ["1", "2", "3"]|user-defined-sep|["1", "2", "3"](user-defined-line-break) print #=> *Be printed when nothing is given to print func*(user-defined-line-break)
-
puts在输出数组时,无论各个元素在数组中嵌套多深,数组中的每个元素都将独占一行输出。如果数组中包含nil元素,在输出nil时将打印出一个空行。
puts [[1, nil, 2],[[]],[3, nil, 4, 5]]
输入出结果:
1 2 3 4 5