开发者

Ruby Configure IRB to Pretty_Inspect by Default

开发者 https://www.devze.com 2022-12-11 04:37 出处:网络
I\'m fairly 开发者_开发技巧new to ruby, and am configuring IRB. I like pretty print (require \'pp\'), but it seems a hassle to always type ppfor it to pretty print it. What I\'d like to do is make it

I'm fairly 开发者_开发技巧new to ruby, and am configuring IRB. I like pretty print (require 'pp'), but it seems a hassle to always type pp for it to pretty print it. What I'd like to do is make it pretty print by default, so if i have a var , say, 'myvar', and type myvar, it automatically calls pretty_inspect instead of the regular inspect. Where do I get started? Ideally, I would be able to add a method to my .irbrc file that is automatically called. Any ideas?

Thanks!


Pretty printing objects by default in irb is exactly what hirb was made to do. These posts explain how hirb can convert pretty much anything into an ascii table. Although hirb is meant to be configured per class, you could have all objects displayed as tables:

# put this in ~/.irbrc
require 'rubygems'
require 'hirb'
Hirb.enable :output=>{'Object'=>{:class=>:auto_table, :ancestor=>true}}

# in irb
>> %w{three blind mice}
+-------+
| value |
+-------+
| three |
| blind |
| mice  |
+-------+
3 rows in set

>> 1..5
+-------+
| value |
+-------+
| 1     |
| 2     |
| 3     |
| 4     |
| 5     |
+-------+
5 rows in set

>> {:a=>1, :b=>2}
+---+---+
| 0 | 1 |
+---+---+
| a | 1 |
| b | 2 |
+---+---+
2 rows in set

This related overflow solution also has an example of hirb in action.


when irb starts, it reads .irbrc from your $HOME directory. If you edit (or create) that file and add

require 'pp'

it will be loaded each time you start irb.

Check out this addition to pretty_print method lists too. Toss that in your .irbrc and you can do :

>> 5.pm
                      %(arg1)         Fixnum
                      &(arg1)         Fixnum
                      *(arg1)         Fixnum
                     **(arg1)         Fixnum
                      +(arg1)         Fixnum
                     +@()             Fixnum(Numeric)
                      -(arg1)         Fixnum
                     -@()             Fixnum
                      /(arg1)         Fixnum
                     <<(arg1)         Fixnum
                     >>(arg1)         Fixnum
                     [](arg1)         Fixnum
                      ^(arg1)         Fixnum
                    abs()             Fixnum
                    ago(arg1, ...)    Fixnum(ActiveSupport::CoreExtensions::Numeric::Time)
               between?(arg1, arg2)   Fixnum(Comparable)
                   byte()             Fixnum(ActiveSupport::CoreExtensions::Numeric::Bytes)
                  bytes()             Fixnum(ActiveSupport::CoreExtensions::Numeric::Bytes

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号