Today I decided to make a short post about how to print an object’s internal state.

puts

Usually when we want to print out something in Ruby, the first method that comes to our mind is puts. The method puts prints all the arguments we pass in to it and inserts a new line after each of them:

That was nice for strings but, what happens if we define a class and try to print an instance of it? Lets define a class Person and create an instance to find out

If we print the instance with puts

Internally puts sends the message to_s to the person object in order to render it as a string. As our Person class doesn’t override to_s, puts simply writes the name of the object’s class (Person), followed by a colon and the object’s unique id in hexadecimal, all surrounded by #<   >, which is the default implementation of to_s inherited from Object.

p

If we simply want to print all the instance variables with the class name and the id in hexadecimal as we saw before, there is a shortcut. The method p will accomplish that because it sends inspect to each object, instead of to_s, and then inserts a new line

Please bear in mind that while puts returns nil after printing, p returns the object itself.

Overriding to_s

As you can see using puts doesn’t reveal anything about the object’s internal state, but remember we said that puts sends to_s to each object it receives as a parameter. A common pattern in Ruby if we want to print something different, is overriding to_s and customizing it to our needs

In this case I have done it to mimic what inspect would do, but we could customize it further to print whatever we want.

Conclusion

If your goal is to write the object’s internal state and you want a recommendation, I would go for puts, mostly because when overriding to_s you have control of the things you want to expose from the object’s internal state and how you expose them.

That was all about this short topic, see you soon raparigos!