views:

39

answers:

2

How can I print a large variable nicely in an irb prompt? I have a variable that contains many variables which are long and the printout becomes a mess to wade through. What if I just want the variable names without their values? Or, can I print each one on a separate line, tabbed-in depending on depth?

+4  A: 

Or, can I print each one on a separate line, tabbed-in depending on depth?

Use pp (pretty print):

require 'pp'
very_long_hash = Hash[(1..23).zip(20..42)]
pp very_long_hash
# Prints:
{1=>20,
 2=>21,
 3=>22,
 4=>23,
 5=>24,
 6=>25,
 7=>26,
 8=>27,
 9=>28,
 10=>29,
 11=>30,
 12=>31,
 13=>32,
 14=>33,
 15=>34,
 16=>35,
 17=>36,
 18=>37,
 19=>38,
 20=>39,
 21=>40,
 22=>41,
 23=>42}
sepp2k
+2  A: 

If you want something that is even more awesome than "pretty" print, you can use "awesome" print. And for a truly spaced out experience, sprinkle some hirbal medicine on your IRb!

Hirb, for example, renders ActiveRecord objects (or pretty much any database access library) as actual ASCII tables:

+-----+-------------------------+-------------+-------------------+-----------+-----------+----------+
| id  | created_at              | description | name              | namespace | predicate | value    |
+-----+-------------------------+-------------+-------------------+-----------+-----------+----------+
| 907 | 2009-03-06 21:10:41 UTC |             | gem:tags=yaml     | gem       | tags      | yaml     |
| 906 | 2009-03-06 08:47:04 UTC |             | gem:tags=nomonkey | gem       | tags      | nomonkey |
| 905 | 2009-03-04 00:30:10 UTC |             | article:tags=ruby | article   | tags      | ruby     |
+-----+-------------------------+-------------+-------------------+-----------+-----------+----------+
Jörg W Mittag