1

Array.inspect returns its output in a flat line:

aoa = [ [1,2,3], [4,5,6] ]
puts aoa.inspect # => [[1, 2, 3], [4, 5, 6]]

Is there an easy way to get an indented output instead? The exact format (e.g., whether there is a line break after the first [) is not important to me. 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
          ]
        ];

The solution should support hashes as well and handle other things gracefully.

sawa
  • 165,429
  • 45
  • 277
  • 381
AnoE
  • 8,048
  • 1
  • 21
  • 36
  • 2
    Those preparing answers will cut and paste your code and then delete all `irb(main):001:0>`. Why not save them the trouble of the second step? – Cary Swoveland Jul 26 '16 at 11:37
  • Thank you, Mladen, for whatever reason I did not find the question you linked. Problem solved. – AnoE Jul 26 '16 at 11:56
  • 1
    You should write "@Miaden", rather than "Miadan", so that SO will notify the person that a comment has been left for them.. – Cary Swoveland Jul 26 '16 at 14:50

2 Answers2

5

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
#     ]
#   ]        
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • I would not install a gem for such a simple, lightweight and already stdlib implemented (http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-pretty_generate) function. – siegy22 Jul 26 '16 at 11:45
  • I used to use `puts xxx.inspect` while debugging test code; `ap xxx` now works fine in the Cucumber environment that is quite colored already. Going with this answer, but anyone feel free to check the linked question that this is a duplicat of. – AnoE Jul 26 '16 at 12:00
-1

I think JSON.pretty_generate is what you are looking for.

require 'json'
puts JSON.pretty_generate(["asdf", [1, 2, 3]])

outputs:

[
  "asdf",
  [
    1,
    2,
    3
  ]
]

and for hashes:

puts JSON.pretty_generate({a: 1, b: 2, c: {x: 1234}})

outputs:

{
  "a": 1,
  "b": 2,
  "c": {
    "x": 1234
  }
}
sawa
  • 165,429
  • 45
  • 277
  • 381
siegy22
  • 4,295
  • 3
  • 25
  • 43
  • By doing this, you will lose information. You will lose distinction between string keys and hash keys of a hash. This cannot be a substitute to inspection. – sawa Jul 26 '16 at 14:57
  • @sawa Do you really have hashes like `{a: 1, "a" => 2}`? I thinks it's a good way to pretty print a hash as well as arrays. – siegy22 Jul 27 '16 at 11:54