15

I findy myself doing a lot of puts .inpsect s in my functional testing to make sure I know how the data is formatted... but hashes are hard to read when there is no new lines after each entry in a hash object. Is there anyway, maybe a gem?, to pretty print hashes?

So that it looks something like this:

{ 
  entry1 => { 
              entrey1.1 => 1,
              entry1.2 => 3
            },
  entry2 => 3
}

instead of: { entry1 => { entrey1.1 => 1, entry1.2 => 3}, entry2 => 3 } ?

Thanks!

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352

2 Answers2

28

you could use the awesome_print gem for that.

https://github.com/michaeldv/awesome_print

require 'awesome_print' # if you like to have it in irb by default, add it to your irbrc
>> ap({:a => 1, :b => [1,2,3], :c => :d})
{
    :b => [
        [0] 1,
        [1] 2,
        [2] 3
    ],
    :a => 1,
    :c => :d
}

btw, instead of puts object.inspect you can also just use p object which calls inspect in the object before printing it. another way to print objects a little nicer than the default puts is to use pp from the ruby stdlib ( http://ruby-doc.org/stdlib/libdoc/pp/rdoc/index.html )

microspino
  • 7,693
  • 3
  • 48
  • 49
Pascal
  • 5,879
  • 2
  • 22
  • 34
4

You could always redefine Hash#inspect in your .irbrc file if you'd like, format them any way you want. That will only affect your interactive environment. An alternative is to express them as YAML which is often more readable. For instance:

def y(object)
  puts object.to_yaml
  return
end

This way you can run y on objects as you might p today.

tadman
  • 208,517
  • 23
  • 234
  • 262