Differences between p and puts in Ruby: rubyputs

Source: Internet
Author: User

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.

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.