Is there any difference between p
and puts
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.
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"
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.
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 .
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
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With