Ruby Tip: Stop using puts object.inspect—use p instead

Posted by Trey Sat, 15 Mar 2008 21:36:00 GMT

I’ve just started reading the new ‘The Ruby Programming Language’ (the hummingbird, not the pickaxe) book by David Flanagan and Yukihiro Matsumoto (Matz). So far, it’s great. I picked up ruby like most of the other language I know—brute force through using it. While it’s nice to learn about things by researching what you need to address the current problem you’re facing, you do tend to miss some of aspects of the language. If you didn’t know it could be done, why would you go looking for how to do it? Usually, these are the aspects that set the language apart from others, after all, that’s why it’s not those other languages.

While I’ve read my share of ruby code by people who do know the language inside and out, I’ve finally decided to dig deep and learn about all of those things I skimmed over getting the general idea about how they worked.

So, through this process, I thought I’d share what I find in the book that I didn’t know before. Of course, you should probably set some time aside for yourself to cozy up with the book yourself.

First tip: ‘p object’ does the same as ‘puts object.inspect’. No more do you have to remember to add that .inspect when you are debugging and outputting stuff to the logger.

If we have a user, u:

>> puts u
#<User:0x1778d18>
=> nil
>> p u
#<User id: 3, username: "myusername", password: "2e14975672723cd9b93df192d2f45aa3b1d3ecb4", change_password: false, email: "myemail@email.com", firstname: "Test", lastname: "User", token: nil, token_expiration: nil, created_at: "2005-12-21 19:15:01", updated_at: "2006-01-12 06:39:17", logged_in_at: "2007-09-18 14:59:48", times_logged_in: 45, email_me: true, cancelled: false>
=> nil
>> 

Nice!

Trackbacks

Use the following link to trackback from your own site:
http://blog.12spokes.com/trackbacks?article_id=ruby-tip-stop-using-puts-object-inspect%E2%80%94use-p-instead&day=15&month=03&year=2008

Comments

Leave a response

Comments