Ruby: Rubocop-friendly Hash pretty-printer

You’re desperate. Your legacy code-generation code outputs a Hash using hash#to_s. You’ve flouted many Rubocop rules to get to where you are. Suddenly, it gets too much. You search the Web for a pretty-print function that you want: a Rubocop-friendly Hash pretty-printer.

Empty-handed, you cough up blood, while a police car’s red-blue lights flicker in through the blinds of your run-down office.

sethw-cop-car-lights

With tired fingers, you type out something like:

# @param hash [Hash]
# @return [String] rubocop-friendly pretty-printed hash
def pretty_print_hash(hash)
with_19_keys = hash.to_s.gsub(/:(\w+)=>/, '\1: ')
with_whitespace = with_19_keys.sub(/^{/, '{ ').sub(/}$/,' }')
with_single_quotes = with_whitespace.gsub(/: \"([^"']*)\"/, ': \'\1\'')
end

Then, you faint, blessed sleep converges on you and envelopes you in a colorless void.

Photo credit: sethw

Published by Olle Jonsson

Human. Wears glasses and often a smile.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.