Best Way to Pretty Print a Hash

Best way to pretty print a hash


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.)

How to pretty print nested dictionaries?

I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:

def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))

More beautiful, indented, pretty-printing

You might want to try the AwesomePrint gem which would return the following by default (the actual output is colored) and is customizable:

aoa = [ [1,2,3], [4,5,6] ]
#=> [
# [0] [
# [0] 1,
# [1] 2,
# [2] 3
# ],
# [1] [
# [0] 4,
# [1] 5,
# [2] 6
# ]
# ]

Parsing a hash to print into a nicely formatted string

You could use the following code:

array = [{"type"=>"work", "value"=>"work@work.com"}, {"type"=>"home", "value"=>"home@home.com"}]

string = array.map do |item|
item = "#{item['type'].capitalize}: #{item['value']}"
end.join(", ")

puts string

Output:

Work: work@work.com, Home: home@home.com, Home: home2@home2.com

How to make Rails.logger.debug print hash more readable

Nevermind, I found the answer to my own question. I need to use

my_hash = {'a' => 'alligator', 'b'=>'baboon'}
Rails.logger.debug "#{my_hash.inspect}"

Then, it looks like

{"b"=>"baboon", "a"=>"aligator"}

How can I print a PowerShell hash object as a hash object?

This ConvertTo-Expression cmdlet can serialize most (recursive) objects to a PowerShell expression:

$x | ConvertTo-Expression
@{
'c' = @{'foo' = 'bar'}
'b' = 2
'a' = 1
}


Related Topics



Leave a reply



Submit