Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created April 26, 2019 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/d4f2b19687b0f73dcbba5f40111b445c to your computer and use it in GitHub Desktop.
Save troelskn/d4f2b19687b0f73dcbba5f40111b445c to your computer and use it in GitHub Desktop.
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