Differences between p and puts in Ruby: rubyputs
P and puts are especially common methods in Ruby. Many children's shoes may think that they are similar and do not pay attention to them when using them. However, they are obviously different from each other after careful consideration.
Here is an example.
Copy codeThe Code is 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 Code is
Copy codeThe Code is 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, while puts obj is equivalent to puts obj. to_s. The ease of use is obviously different. p is the inspect method of obj, while puts is the to_s method.
Why? I think we can start with the difference between to_s and inspect. to_s is the string representation of the object, and is the method used by puts and double quotation marks. Inspect is a representation of the object state and is generally used in debug. The to_s and inspect methods are defined in the Object. By default, both the Class Name and address of the returned Object are returned.
Therefore, p and puts are mainly used for different purposes. p is used as the debug output, while puts is used as the object string to represent the 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 usually uses the inspect method of the object.