P and the puts is a Ruby The most commonly used methods, many children's shoes may think they are similar, the use of the time is not paid attention to, but carefully looked up, they are clearly different.
Let me give you an example:
class Foo
def inspect
"foo from inspect"
end
def to_s
"Foo from to_s"
End
End
Foo=Foo.new
P foo
puts foo
p Span style= "Color:green;" > "P: < #{ foo } >
puts "puts: < Foo > "
The output of this code is:
P obj equivalent puts Obj.inspect
puts obj equivalent puts obj.to_s
use is obviously different. , p is using obj inspect method, while puts Yes to_s method.
Why is that? This I think can be from to_s and inspect to_s is the string representation of the object, Yes puts and double quote characters using the method. inspect is the representation of the state of the object, which is used for Span style= "Font-family:tahoma;" > debug Object defined in to_s and inspect method, the default is the class name and address of the returned object.
so p and puts p debug output, and puts
It is also worth mentioning that the IRB Console , the expression in the command line evaluates, using the P object that Inspect method. In addition, the debug output command is usually the inspect method that uses the object .
One more example:
Array=[2,4 6 8 10
array
p array
print array
Summary:
print
compare items |
puts | " TD style= "Border-top:solid Silver 0.75pt; Border-left:none; Border-bottom:solid Silver 0.75pt; Border-right:solid Silver 0.75pt; padding:5px; "valign=" middle ">
|
line break |
Add line breaks at the end |
end without line break |
Add line breaks at the end |
output of non-string objects |
Call the to_s method of the object |
Call the to_s method of the object |
Convert an object to a string by using the inspect method |
(add 1) The P, puts, and print comparisons in Ruby