Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby pretty print with rubocop standard syntax
class RubyPrint
def self.pp(mixed)
puts new.transform(mixed)
end
def transform(mixed, indentation = 1)
if mixed.is_a?(Hash)
transform_hash mixed, indentation
elsif mixed.is_a?(Array)
transform_array mixed, indentation
elsif mixed.is_a?(Date)
"Date.parse(#{mixed.inspect.inspect})"
elsif mixed.is_a?(Time)
"Time.parse(#{mixed.inspect.inspect})"
else
mixed.inspect
end
end
def transform_hash(hash, indentation = 1)
indent_string = " " * indentation
buffer = []
buffer << "{"
compiled = hash.map do |key, item|
indent_string + key.to_s + ": " + transform(item, indentation + 1)
end
buffer << compiled.join(",\n")
buffer << (" " * (indentation - 1)) + "}"
buffer.join("\n")
end
def transform_array(array, indentation = 1)
return "[]" if array.empty?
return "[#{transform(array.first, indentation)}]" \
if array.size == 1
indent_string = " " * indentation
buffer = []
buffer << "["
compiled = array.map do |item|
indent_string + transform(item, indentation + 1)
end
buffer << compiled.join(",\n")
buffer << (" " * (indentation - 1)) + "]"
buffer.join("\n")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.