00:00
02:29

RFS: p vs puts Method - 016

The puts method in ruby is very popular all over the internet it's generally used by ruby programmers for debugging purposes and ot output the value of certain variables so we can see what's goin on in our system. However puts can sometimes lead you astray because of how it converts everything into a string.

Let's take a look at the differnet between the p and puts method call

Kernel#puts

puts 11=> nilputs '1'1=> nil

We can see that eventhough we are putting out an integer in one case and string in another the output is exactly the same and it's pretty much impossible to make out the different between the 2 data types.

Kernel#p

p 11=> 1p '1'"1"=> "1"

We can clearly see the difference between p and puts. Kernel#p will preserve the data type in the output so you'll be able to see the difference between them.

Let's try another example

puts ['dog', 'cat']dogcat=> nil
p ['dog', 'cat']["dog", "cat"]=> ["dog", "cat"]

Here the advantage of using p is even more clear. When we use puts on an array we don't know that the output is an array. But with p we can clearly see that it's an array.