A brief analysis of the use of P and puts in Ruby _ruby special topics

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.