33

Is there a way to make the output of inspect more readable?

In Perl, there is Data::Dumper which makes the output more easy to read.

5 Answers 5

39

The ruby standard library contains PP (short for "Pretty Print"), which formats structures much better than the standard inspect:

http://www.ruby-doc.org/stdlib/libdoc/pp/rdoc/index.html

You need to require 'pp' at the top of your source file before you can use it, and then just replace p obj with pp obj in your code.

I find it really useful for hashes and arrays in particular!

1
  • 7
    PP will also add pretty_inspect() to the Kernel Module, so you can simply replace calls to inspect() with that.
    – tjbp
    Dec 9, 2016 at 17:43
9

like @tjbp said, just simply use pretty_inspect() instead of inspect()

it will give you nice line break and indentation

8

Beside the 'pp' solution, yaml may be a solution.

Try:

require 'yaml'
puts [1,2,3=>'three'].to_yaml

You get:

--- 
- 1
- 2
- 3: three

And a complete different approach: Write your own inspect-code if you have a inspect-problem with a specific class

Example:

class MyTest
  def initialize()
    @created = Time.now
  end
  def inspect()
    "Hi, I'm the objected created at #{@created}. That's #{Time.now - @created} seconds ago"
  end
end

x = MyTest.new
sleep 5
puts x.inspect

You get

Hi, I'm the objected created at 2011-06-28 12:48:38 +0100. That's 5.0 seconds ago
2
  • 1
    I like this solution best. I don't even have to require 'yaml' when using rails console. Thanks for posting
    – Ira Herman
    Jun 17, 2013 at 9:44
  • YAML is the way to go!
    – Andrey
    Mar 10, 2020 at 21:29
6

Try awesome_print: http://www.rubyinside.com/awesome_print-a-new-pretty-printer-for-your-ruby-objects-3208.html

0

This will work and look great :)

in your gemfile:

group :development do
  gem 'table_print', '~> 1.5.3'
end

in your view:

<pre>
<%= TablePrint::Printer.new(@users, []).table_print %>
</pre>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.