Skip to content

Instantly share code, notes, and snippets.

@archan937
Last active December 12, 2015 08:29
Show Gist options
  • Save archan937/4744955 to your computer and use it in GitHub Desktop.
Save archan937/4744955 to your computer and use it in GitHub Desktop.
A simple Ruby method which returns an inspection string of the passed object with pretty indention ^^
def pretty_inspect(object, indent = 2)
if object.is_a?(Array)
entries = object.collect{|x| "#{pretty_inspect x, indent + 2}"}
pretty_indent entries, "[", "]", indent
elsif object.is_a?(Hash)
entries = object.keys.sort.collect{|x| "#{pretty_inspect x} => #{pretty_inspect object[x], indent + 2}"}
pretty_indent entries, "{", "}", indent
else
object.inspect
end
end
def pretty_indent(entries, open, close, indent)
if (s = "#{open}#{entries.join ", "}#{close}").size < 30
return s
end
entries.each_with_index{|x, i| entries[i] = "#{x}," if i < entries.size - 1}
[open, entries].flatten.join("\n" + (" " * indent)) + "\n" + (" " * (indent - 2)) + close
end
1.9.3-p374 :001 > require "./pretty_inspect.rb"
=> true
1.9.3-p374 :002 > puts pretty_inspect({:a => {:b => [1, 2, 3, {:c => ["a", "b", "c"]}]}, :d => 4})
{
:a => {
:b => [
1,
2,
3,
{:c => ["a", "b", "c"]}
]
},
:d => 4
}
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment