P and puts are the most commonly used methods in Ruby, and many children's shoes may think they are similar and are not noticed when they are used, but they are obviously different when they are carefully studied.
Let me give you an example.
Copy Code code as follows:
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 "P: <#{foo}>"
Puts "P: <#{foo}>"
The output of this piece of code is
Copy Code code as follows:
Foo from inspect
Foo from to_s
P: <foo from to_s>
Puts: <foo from to_s>
P obj is equivalent to puts Obj.inspect, and puts obj is equivalent to puts obj.to_s, the convenience of use is significantly different, p is the inspect method using obj, and puts is the to_s method.
Why is that? This I think can be said from the difference between to_s and inspect, to_s is a string representation of an object, a method used by puts and double quote characters. Inspect is a representation of the state of an object and is commonly used in debug. The to_s and inspect methods are defined in object, and the default is to return the class name and address of the object.
So p and puts are mainly different uses, p is the debug output, and puts is the string representation of the object as output.
It is also worth mentioning that in the IRB console, the expression in the command line is evaluated using the inspect method of the P object. In addition, the debug output command is usually the inspect method of using the object.