(add 1) The P, puts, and print comparisons in Ruby

Source: Internet
Author: User

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

" 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 ">

compare items

 puts

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

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.