My .irbrc for console/irb

Posted by Dr Nic on October 12, 2006

The relatively unspoken warhorse of Ruby/Rails programming is the irb/console [1]. Ruby is such a joy to work with in part from this one development tool.

I got tired of typing require 'pp' and the like each time I loaded up my console, that I was joyed to discover I could configure it: using the .irbrc file (win32 explanation below).

Here is mine:

require 'irb/completion‘
require ‘map_by_method‘
require ‘what_methods‘
require ‘pp‘
IRB.conf[:AUTO_INDENT]=true

Here is what each line does:

Line 1 - Auto-completion in IRB

You can discover what methods can be called on an object. Double-TAB is your “exploration” combo.

irb(main):001:0> "hello".to_<double TAB here>
.to_a    .to_f    .to_i    .to_s    .to_str  .to_sym
irb(main):003:0> a = “hello”
=> “test”
irb(main):004:0> a.t<double TAB here>
a.taint     a.to_f      a.to_str    a.tr!       a.type
a.tainted?  a.to_i      a.to_sym    a.tr_s
a.to_a      a.to_s      a.tr        a.tr_s!

Not understanding this? Watch the video

Line 2 - Map by Method

When in the console its great to be able to explore and manipulate data as quickly as possible. The Map by Method (previously called Map by Pluralisation) is wizardly for quick-to-type array manipulations.

See the original and demo articles.

To install:

gem install map_by_method

Line 3 - MethodFinder/Object.what?

Ever asked: “if I have an object, what method can I call on it to get that result?”

See if this suits your console cravings:

> 3.45.what? 3
3.45.truncate == 3
3.45.to_i == 3
3.45.prec_i == 3
3.45.floor == 3
3.45.to_int == 3
3.45.round == 3
=> ["truncate", "to_i", "prec_i", "floor", "to_int", "round"]
> 3.45.what? 4
3.45.ceil == 4
=> ["ceil"]
> 3.55.what? 4
3.55.ceil == 4
3.55.round == 4
=> ["ceil", "round"]

Just what you need in the console.

I’ve gemified a library found on _why’s blog by Nikolas Coukouma.

To install:

gem install what_methods

Line 4 - pretty print

pp = pretty print - wondeful in the console for exploring objects that are visually large.

Thusly demonstrated:

> me = {:name => “Nic Williams”, :country => “Netherlands”, :city => “Amsterdam”, :tags => %w(ruby rails javascript)}
=> {:country=>”Netherlands”, :name=>”Nic Williams”, :city=>”Amsterdam”, :tags=>["ruby", "rails", "javascript"]}
irb(main):017:0> pp me
{:country=>”Netherlands”,
 :name=>”Nic Williams”,
 :city=>”Amsterdam”,
 :tags=>["ruby", "rails", "javascript"]}
=> nil

It prints, and its pretty.

Line 5 - auto-tabbing turned on

Auto-tabbing is the console’s way of trying to help your code look pretty by indenting your blocks, etc.

It’s only primitive, but better than a kick in the teeth.

> [1,2,3].each do |a|
*     puts a
>   end
1
2
3
=> [1, 2, 3]

.irbrc for Win32

Create a file called anything you like (e.g. “_irbrc” or “irb.rc”) and place it anywhere you like (say C:\Documents and Settings\), and set that full path to the ENV variable IRBRC, e.g. C:\Documents and Settings\\_irbrc

More ideas at the bottom of this.

Epilogue

Any other useful libraries to include in irb/console?

[1] You can run irb from anywhere, but to use console for a specific rails app, you need to point to the console script for that app, e.g ruby script/console from the rails app root folder.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Jeff Thu, 12 Oct 2006 16:17:41 UTC

    Awesome tip about the IRBC environment variable on win32, Dr. Nic. Thanks a lot.

  2. Rob Sanheim Thu, 12 Oct 2006 17:17:40 UTC

    You forgot local methods:

    class Object
      # Return a list of methods defined locally for a particular object.  Useful
      # for seeing what it does whilst losing all the guff that's implemented
      # by its parents (eg Object).
      def local_methods(obj = self)
        (obj.methods - obj.class.superclass.instance_methods).sort
      end
    end
    
  3. Rob Sanheim Thu, 12 Oct 2006 17:18:08 UTC

    Wow that turned out ugly - if you could edit it to ruby color it that would be greeeeat.

  4. Chris Thu, 12 Oct 2006 18:53:39 UTC

    Rob: You can just do object.methods(false). If you pass false into methods, instance_methods, public_instance_methods, etc, it will omit methods defined higher up in the hierarchy.

  5. Dr Nic Thu, 12 Oct 2006 18:59:27 UTC

    @rob - <pre> is the magic.

    @chris - cool - defn hadn’t noticed that before. One upside to local_methods is that it requires no more typing than a few characters + double-TAB.

  6. Rob Sanheim Thu, 12 Oct 2006 19:17:20 UTC

    Chris: Nope, they do different things. I see that methods(false) has no rdoc in the official api, so I’m not quite sure what the differences are. But just try the two on a ActiveRecord model, for instance.

    I think that local_methods keeps things defined in the included modules, whereas methods(false) omits them.

  7. Ian Ozsvald Fri, 13 Oct 2006 10:39:56 UTC

    Hi Dr. Nic - thanks for linking to our video, Eric Lake did a great job there with his first ShowMeDo.

    We’d love to have some more Ruby content, to go alongside our growing (36+) Python and Java (15+) videos, learning-by-watching seems to work very well for programming/configuration tasks.

    Might anyone be interested in having a go? You could be up and running within an hour, all with open-source software and we take care of the heavy-lifting.

  8. Chris Fri, 13 Oct 2006 19:37:14 UTC

    Rob: Passing false to methods or any related method omits any methods defined elsewhere. Since local_methods just cuts out instance_methods of the superclass, it won’t really work as intended on classes (for instance) and it won’t catch Modules (as you pointed out).

    To Nic’s point, I think I’m going to define local_methods as methods(false) since it is really handy to have the tab-complete locked and loaded.

  9. Dr Nic Fri, 13 Oct 2006 20:09:51 UTC

    @chris, so you prefer something like:

    class Object
      # Return a list of methods defined locally for a particular object.  Useful
      # for seeing what it does whilst losing all the guff that's implemented
      # by its parents (eg Object).
      def local_methods(obj = self)
        obj.methods(false).sort
      end
    end
    

    But this is currently returning an empty array for me @ the moment. I’ve sent you an email and we’ll sort this out :)

  10. Chris Fri, 13 Oct 2006 20:43:04 UTC

    Oh I’m so busted. I think the method you guys are proposing works best. I was thinking exclusively of user-defined classes, which is obviously wrong.

  11. evan Mon, 16 Oct 2006 17:47:23 UTC

    Great stuff. local_methods auto-completes oddly for me, though:

    chloe:~ eweaver$ irb
    irb(main):001:0> 3.local_methods
    irb(main):002:0> “string”.local_methods”

    Where’s that double quote coming from? I guess it happens on all methods that don’t have a corresponding ! sibling to block the strange completion.

  12. Grant Hutchins Wed, 18 Oct 2006 07:29:24 UTC

    I can’t get pretty print to work, does it require a gem?

  13. Dr Nic Wed, 18 Oct 2006 07:47:37 UTC

    @grant - looks like its std Ruby - pp

    Can you get it to work in irb if you you type require 'pp' there?

    Perhaps add require 'rubygems' to your .irbrc file.

  14. Dr Nic Wed, 18 Oct 2006 10:47:16 UTC

    Brilliant examples on Ruby Forum thread

  15. Piggybox Fri, 20 Oct 2006 09:17:36 UTC

    Hi Dr. Nic, this post is especially useful and I find the wirble gem is nice a nice complement. Just add more 3 lines:

    require ‘wirble’
    Wirble.init
    Wirble.colorize unless Config::CONFIG['host_os'] == ‘mswin32′

    Unfortunately, Windows console is color-blinded :)

    Also, I find setting the IRBRC env in Linux is still necessary for Rails console to work as desired, cause it seems to ignore the .irbrc file. Dunno why.

  16. Nicolas Sun, 26 Nov 2006 14:20:28 UTC

    There is a little problem with your quote/backquote mixing

    require ‘irb/completion‘
    require ‘map_by_method‘
    require ‘what_methods‘

  17. Giles Bowkett Mon, 22 Jan 2007 07:17:14 UTC

    You may like Wirble, it enables syntax coloring in irb.

    http://pablotron.org/software/wirble/

  18. J Dugan Tue, 20 Feb 2007 03:11:55 UTC

    Thanks, very helpful.

  19. bryan Sat, 24 Feb 2007 06:30:06 UTC

    Works the same on Linux :) Only some distros don’t include headers for curses. See http://blog.nanorails.com/articles/2006/03/06/installing-readline-on-kubuntu

    for a fix

  20. dodo Wed, 07 Mar 2007 07:35:03 UTC

    Hey, do you guys know of any way to extend readline?
    I’ve added some of my own commands to use script/console as an IDE:

    http://blog.dominiek.com/articles/2007/03/05/destroying-the-wall-between-writing-and-executing-code

  21. Dr Nic Wed, 07 Mar 2007 07:53:13 UTC

    @dodo - I am in love with your .irbrc

  22. Dr Nic Wed, 18 Jul 2007 09:25:08 UTC

    BTW, if you want to add active_support to .irbrc, and you use Edge Rails, you must not preload the gem if its a rails console.

    So instead of

    require 'active_support'

    Use:

    unless IRB.conf[:LOAD_MODULES].join =~ /config\\/environment/
      require ‘active_support’
    end
    

    Until I did this I was getting errors like:

    /vendor/rails/railties/lib/dispatcher.rb:94:NoMethodError: undefined method `attr_accessor_with_default' for #<Class:Dispatcher>
  23. stephaneliu Thu, 26 Jul 2007 10:05:13 UTC

    I can modify the irbrc file on my windows machine but not on my mac that runs locomotive. I modified irbrc file in both ~/.irbrc and /…bin/.irbrc. Should the irbrc file be be in another location?

  24. stephaneliu Thu, 26 Jul 2007 10:07:27 UTC

    @stephaneliu [via] -

    parser didn’t like my syntax for second location of irbrc which is in the locomotive home/bin directory.

  25. Dr Nic Thu, 26 Jul 2007 10:32:10 UTC

    @stephaneliu [via] - it is funny seeing “@stephaneliu” when you are replying to yourself. I might add “@me” and it could point to the previous comment (which we’d assume was your own).

  26. Jim OLeary Thu, 18 Oct 2007 12:32:49 UTC

    (I find) another useful method to add to your irbrc is :

    def self.load_rails(from=”./”)
    require File.expand_path(File.join(from,”config/boot”))
    require File.join(RAILS_ROOT, ‘config’, ‘environment’)
    end

    it loads a rails project into irb, useful if you really should have run ./script/console ;-)

  27. Daniel Sun, 06 Apr 2008 16:43:41 UTC

    @Piggybox [via] -

    I’m not sure that’s true. Python has this thing called ipython which seems to work within windows cmd. Dito for cygwin. If someone knows how to make wirble work in windows, that’d be great.

  28. Ted Naleid » Syntactic Sugar in Groovy and Ruby Wed, 28 May 2008 14:53:29 UTC

    [...] the .irbrc file auto load ruby code when going into irb (the interactive ruby shell. Having a .groovyrc file that gets loaded when [...]

Comments