Pretty Printing in ruby

Say you have a complex object like:

state = {a: 1, b: '2', c: [3, 4, 5]}

And you want to display it nicely to standard output. Then you do:

require 'pp'

pp state
# {:a=>1, :b=>"2", :c=>[3, 4, 5]}

Amazing! But you might want to save that into a string so it can be used later, like in the ouput of your logger. For this usecase you can call .pretty_inspect on any object and pass that result around.

result = state.pretty_inspect

puts result
# {:a=>1, :b=>"2", :c=>[3, 4, 5]}

This should have the same effect as pp state but now you can do stuff with it:

require 'logger'

logger = Logger.new(STDOUT)
logger.warn("Result is: #{result}")
# W, [2020-07-22T18:48:55.386144 #16069]  WARN -- : Result is: {:a=>1, :b=>"2", :c=>[3, 4, 5]}