214

I have a large hash with nested arrays and hashes. I would like to simply print it out so it 'readable' to the user.

I would like it to be sort of like to_yaml - that's pretty readable - but still too tech looking.

Ultimately its going to be end users who need to read these data chunks so they need to be formatted cleanly.

Any suggestions?

2

14 Answers 14

307
require 'pp'
pp my_hash

Use pp if you need a built-in solution and just want reasonable line breaks.

Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false option to turn off displaying array indices.)

1
  • pp is nice, but it is really a pity that one cannot limit the depth.
    – akim
    Apr 20, 2020 at 14:02
125

If you have JSON, I recommend JSON.pretty_generate(hash) because it is simpler than awesome_print, looks great in a pre tag, and allows for easy copying from a web page. (See also: How can I "pretty" format my JSON output in Ruby on Rails?)

5
  • This answer would benefit from an actual example Oct 28, 2014 at 1:07
  • @TravisBear There is example output if you click the "see also" link in my answer. I recommend this answer in particular: stackoverflow.com/a/1823885/109618
    – David J.
    Nov 19, 2014 at 3:40
  • 15
    It would be puts JSON.pretty_generate(hash)
    – joeloui
    Sep 3, 2015 at 18:13
  • If you do need to create JSON, allow me to recommend my own (free, OSS, no-ads) library for creating pretty JSON from Ruby or JS: NeatJSON (Ruby) and NeatJSON (Online/JS)
    – Phrogz
    Mar 14, 2016 at 18:46
  • Sorry, I realize now that pretty_generate does accept a Ruby object, not json text.
    – Tony
    Aug 23, 2017 at 23:52
37

Another solution which works better for me than pp or awesome_print:

require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)
2
  • 3
    Note that Pry::ColorPrinter.pp(obj) writes to standard out but can take additional params, including the destination. Like Pry::ColorPrinter.pp(obj, a_logger)
    – Eric Urban
    Mar 24, 2016 at 3:23
  • 1
    I'm surprised this isn't better documented: I always use pry as my Rails console, and I've been looking for a long time how to tap into its pretty-printer without using another gem. Upvoted because this solution finally put an end to my long search. :-)
    – wiz
    Jul 25, 2018 at 7:49
23

If you don't have any fancy gem action, but do have JSON, this CLI line will work on a hash:

puts JSON.pretty_generate(my_hash).gsub(":", " =>")

#=>
{
  :key1 => "value1",

  :key2 => "value2",

  :key3 => "value3"
}
5
  • 9
    Downvoted because this will mess up any keys and values containing ":"
    – thomax
    Sep 20, 2016 at 12:27
  • 1
    This also doesn't deal with null (JSON) vs nil (Ruby).
    – Rennex
    Jun 2, 2017 at 1:11
  • 1
    Still handy for most situations.
    – Abram
    Oct 7, 2019 at 15:00
  • 1
    Can't believe this three years later! Thanks @Abram . :) It's not the most elegant solution in the world but it gets things done in a pinch. Oct 8, 2019 at 11:51
  • I was happy enough with just JSON.pretty_generate(my_hash) Apr 8, 2021 at 18:30
6

Pretty Print Hash using pure Ruby (no gems)

I came across this thread trying to solve this problem for myself.

I had a large Hash that I wanted to make pretty, but I needed to stay in ruby hash notation instead of JSON.

This is the code + examples

  • Use pretty_generate to get a nice formatted JSON string.
  • Replace all the JSON keys with symbol: equivalent
puts JSON.pretty_generate(result)
         .gsub(/(?:\"|\')(?<key>[^"]*)(?:\"|\')(?=:)(?:\:)/) { |_|
              "#{Regexp.last_match(:key)}:"
          }

Sample JSON

{
  "extensions": {
    "heading": "extensions",
    "take": "all",
    "array_columns": [
      "name"
    ]
  },
  "tables": {
    "heading": "tables",
    "take": "all",
    "array_columns": [
      "name"
    ]
  },
  "foreign_keys": {
    "heading": "foreign_keys",
    "take": "all",
    "array_columns": [
      "name"
    ]
  },
  "all_indexes": {
    "heading": "all_indexes",
    "take": "all",
    "array_columns": [
      "name"
    ]
  },
  "keys": {
    "heading": "keys",
    "take": "all",
    "array_columns": [
      "name"
    ]
  }
}

Sample Ruby Hash

{
  extensions: {
    heading: "extensions",
    take: "all",
    array_columns: [
      "name"
    ]
  },
  tables: {
    heading: "tables",
    take: "all",
    array_columns: [
      "name"
    ]
  },
  foreign_keys: {
    heading: "foreign_keys",
    take: "all",
    array_columns: [
      "name"
    ]
  },
  all_indexes: {
    heading: "all_indexes",
    take: "all",
    array_columns: [
      "name"
    ]
  },
  keys: {
    heading: "keys",
    take: "all",
    array_columns: [
      "name"
    ]
  }
}
1
  • I think both \"|\' should simply be \", as JSON.generate won't surround the key with '. Jul 14 at 13:22
5

In Rails

If you need

  • a "pretty printed" Hash
  • in e.g. the Rails.logger
  • that, specifically, runs inspect on the objects in the Hash
    • which is useful if you override/define the inspect method in your objects like you're supposed to

... then this works great! (And gets better, the bigger and more nested your Hash object is.)

logger.error my_hash.pretty_inspect

For example:

class MyObject1
  def inspect
    "<#{'*' * 10} My Object 1 #{'*' * 10}>"
  end
end

class MyObject2
  def inspect
    "<#{'*' * 10} My Object 2 #{'*' * 10}>"
  end
end

my_hash = { a: 1, b: MyObject1.new, MyObject2.new => 3 }

Rails.logger.error my_hash
# {:a=>1, :b=><********** My Object 1 **********>, <********** My Object 2 **********>=>3}

# EW! ^

Rails.logger.error my_hash.pretty_inspect
# {:a=>1,
#  :b=><********** My Object 1 **********>,
#  <********** My Object 2 **********>=>3}

pretty_inspect comes from PrettyPrint, which rails includes by default. So, no gems needed and no conversion to JSON needed.

Not In Rails

If you're not in Rails or if the above fails for some reason, try using require "pp" first. For example:

require "pp"  # <-----------

class MyObject1
  def inspect
    "<#{'*' * 10} My Object 1 #{'*' * 10}>"
  end
end

class MyObject2
  def inspect
    "<#{'*' * 10} My Object 2 #{'*' * 10}>"
  end
end

my_hash = { a: 1, b: MyObject1.new, MyObject2.new => 3 }

puts my_hash
# {:a=>1, :b=><********** My Object 1 **********>, <********** My Object 2 **********>=>3}

# EW! ^

puts my_hash.pretty_inspect
# {:a=>1,
#  :b=><********** My Object 1 **********>,
#  <********** My Object 2 **********>=>3}

A Full Example

Big ol' pretty_inspected Hash example from my project with project-specific text from my inspected objects redacted:

{<***::******************[**:****, ************************:****]********* * ****** ******************** **** :: *********** - *** ******* *********>=>
  {:errors=>
    ["************ ************ ********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
     "************ ************ ********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
     "************ ************ ********** ***** ****** ******** is invalid",
     "************ ************ ********** is invalid",
     "************ ************ is invalid",
     "************ is invalid"],
   :************=>
    [{<***::**********[**:****, *************:**, ******************:*, ***********************:****] :: **** **** ****>=>
       {:************=>
         [{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - ******* ***** - *>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: *** - *>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ********* - *>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ********** - ********** *>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ******** - *>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: **** - *******>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: *** - ********** ***** - *>=>
            {}}]}},
     {<***::**********[**:****, *************:**, ******************:*, ***********************:****] ******************** :: *** - *****>=>
       {:errors=>
         ["************ ********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
          "************ ********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
          "************ ********** ***** ****** ******** is invalid",
          "************ ********** is invalid",
          "************ is invalid"],
        :************=>
         [{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]*********** :: ****>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
            {:errors=>
              ["********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
               "********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
               "********** ***** ****** ******** is invalid",
               "********** is invalid"],
             :**********************=>
              [{<***::*******************[**:******, ************************:***]****-************ ******************** ***: * :: *** - ***** * ****** ** - ******* * **: *******>=>
                 {:errors=>
                   ["***** ****** ******** **** ********** **** ***** ***** ******* ******",
                    "***** ****** ******** **** ********** is invalid"],
                  :***************=>
                   [{<***::********************************[**:******, *************:******, ***********:******, ***********:"************ ************"]** * *** * ****-******* * ******** * ********* ******************** *********************: ***** :: "**** *" -> "">=>
                      {:errors=>["**** ***** ***** ******* ******"],
                       :**********=>
                        {<***::*****************[**:******, ****************:["****** ***", "****** ***", "****** ****", "******* ***", "******* ****", "******* ***", "****"], **:""] :: "**** *" -> "">=>
                          {:errors=>
                            ["***** ******* ******",
                             "***** ******* ******"]}}}}]}}]}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
            {}},
          {<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
            {}}]}}]}}
4

Use the answers above if you're printing to users.

If you only want to print it for yourself in console, I suggest using the pry gem instead of irb. Besides pretty printing, pry has a lot of other features as well (check railscast below)

gem install pry

And check this railscast:

http://railscasts.com/episodes/280-pry-with-rails

3

Easy to do with json if you trust your keys to be sane:

JSON.pretty_generate(a: 1, 2 => 3, 3 => nil).
  gsub(": null", ": nil").
  gsub(/(^\s*)"([a-zA-Z][a-zA-Z\d_]*)":/, "\\1\\2:"). # "foo": 1 -> foo: 1
  gsub(/(^\s*)(".*?"):/, "\\1\\2 =>") # "123": 1 -> "123" => 1

{
  a: 1,
  "2" => 3,
  "3" => nil
}
1

Using Pry you just need to add the following code to your ~/.pryrc:

require "awesome_print"
AwesomePrint.pry!
1
  • This pretty prints every command. I want it to pretty print on instructions, for eg. on when I use pp in the front of the command like this - pp User.last
    – Divij Jain
    May 28 at 9:36
1

Of all the gems I tried, show_data gem worked the best for me, I now use it extensively to log params hash in Rails pretty much all the time

0

For large nested hashes this script could be helpful for you. It prints a nested hash in a nice python/like syntax with only indents to make it easy to copy.

module PrettyHash
  # Usage: PrettyHash.call(nested_hash)
  # Prints the nested hash in the easy to look on format
  # Returns the amount of all values in the nested hash

  def self.call(hash, level: 0, indent: 2)
    unique_values_count = 0
    hash.each do |k, v|
      (level * indent).times { print ' ' }
      print "#{k}:"
      if v.is_a?(Hash)
        puts
        unique_values_count += call(v, level: level + 1, indent: indent)
      else
        puts " #{v}"
        unique_values_count += 1
      end
    end
    unique_values_count
  end
end

Example usage:

  h = {a: { b: { c: :d }, e: :f }, g: :i }
  PrettyHash.call(h)

a:
  b:
    c: d
  e: f
g: i
=> 3

The returned value is the count (3) of all the end-level values of the nested hash.

0

Here's another approach using json and rouge:

require 'json'
require 'rouge'

formatter = Rouge::Formatters::Terminal256.new
json_lexer = Rouge::Lexers::JSON.new

puts formatter.format(json_lexer.lex(JSON.pretty_generate(JSON.parse(response))))

(parses response from e.g. RestClient)

0

I came here through a search engine looking for a way to print hashes to end users in a human-readable format—particularly hashes with underscores in their keys.

Here's what I ended up doing using Rails 6.0.3.4:

hash.map do |key, val|
  key.to_s.humanize + ': ' + val.to_s
end.join('; ')

# Turns {:foo_bar => 'baz', :fee_ber => :bez} into 'Foo bar: Baz; Fee ber: Bez'.
-3

Under Rails, arrays and hashes in Ruby have built-in to_json functions. I would use JSON just because it is very readable within a web browser, e.g. Google Chrome.

That being said if you are concerned about it looking too "tech looking" you should probably write your own function that replaces the curly braces and square braces in your hashes and arrays with white-space and other characters.

Look up the gsub function for a very good way to do it. Keep playing around with different characters and different amounts of whitespace until you find something that looks appealing. http://ruby-doc.org/core-1.9.3/String.html#method-i-gsub

3
  • 7
    Arrays and hashes do not have a built-in to_json method, these are added by ActiveSupport from Rails.
    – Tom De Leu
    Feb 11, 2013 at 14:54
  • It's even worse than normal irb/pry: {"programming_language":{"ruby":{},"python":{}}} Aug 4, 2014 at 9:59
  • 1
    OP did not rule out Rails Feb 5, 2015 at 11:49

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.