Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

p vs puts in Ruby

Tags:

ruby

Is there any difference between p and puts in Ruby?

like image 388
collimarco Avatar asked Aug 10 '09 14:08

collimarco


People also ask

What is difference between puts and P in Ruby?

While the print method allows you to print information in the same line even multiple times, the puts method adds a new line at the end of the object. On the other hand, p is useful when you are trying to understand what your code does, e.g. when you are trying to figure out a certain error.

What does P in Ruby mean?

p is a method that shows a more “raw” version of an object. For example: > puts "Ruby Is Cool" Ruby Is Cool > p "Ruby Is Cool" "Ruby Is Cool"

What's the difference between puts and print?

Hi, The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.

What does puts return in Ruby?

puts(string) in ruby writes the string value into $stdout . For example if you run ruby console in terminal, string will be written into your terminal. At the same time every method in ruby returns something and method puts returns nil .


2 Answers

p foo prints foo.inspect followed by a newline, i.e. it prints the value of inspect instead of to_s, which is more suitable for debugging (because you can e.g. tell the difference between 1, "1" and "2\b1", which you can't when printing without inspect).

like image 181
sepp2k Avatar answered Oct 17 '22 05:10

sepp2k


It is also important to note that puts "reacts" to a class that has to_s defined, p does not. For example:

class T    def initialize(i)       @i = i    end    def to_s       @i.to_s    end end  t = T.new 42 puts t   => 42 p t      => #<T:0xb7ecc8b0 @i=42> 

This follows directly from the .inspect call, but is not obvious in practice.

like image 37
ezpz Avatar answered Oct 17 '22 05:10

ezpz