Last active
December 12, 2015 08:29
-
-
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 ^^
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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