AnoE AnoE - 4 months ago 17
Ruby Question

More beautiful, indented, pretty-printed version of (Array||Hash).inspect?

Array.inspect
works just fine, but returns its output in a flat line:

irb(main):001:0> aoa = [ [1,2,3], [4,5,6] ]
=> [[1, 2, 3], [4, 5, 6]]
irb(main):003:0> puts aoa.inspect
[[1, 2, 3], [4, 5, 6]]


Is there a easy way to get an indented output instead?

The exact format is not important to me (i.e., I won't bother about whether theres a linebreak after the first
[
, or things like that). I just would like to have it more readable.

Compare Perl:

DB<2> print Dumper([[1,2,3],[4,5,6]])
$VAR1 = [
[
1,
2,
3
],
[
4,
5,
6
]
];


Of course, the solution should support hashes as well and handle other things gracefully.

Answer

You might want to try the AwesomePrint gem which would return the following by default (the actual output is colored) and is customizable:

aoa = [ [1,2,3], [4,5,6] ]
#=> [
#     [0] [
#       [0] 1,
#       [1] 2,
#       [2] 3
#     ],
#     [1] [
#       [0] 4,
#       [1] 5,
#       [2] 6
#     ]
#   ]