Search code examples
rubyload-path

Where can I see the source code for classes within my current ruby intallation?


I am new to ruby but nonetheless I have installed various versions of Ruby using RVM, Here's the the output of my LOAD_PATH

ruby-1.9.2-p136 :001 > puts $LOAD_PATH
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/i686-linux

Ok. So the question here is, Where within these directories can I see the source code for classes like Array, or Time ? (I know, it's an extremely n00b question, but I need to know.)

I've been needing to take a look at the source of Array for a long time.

Thanks in advance!

PS. Which class do you recommend looking at if I want to become a better ruby programmer?


Solution

  • The coolest gadget for code browsing I found so far is pry:
    http://pry.github.com/

    It's an irb replacement with a lot of goodies. An example session so you can see how you can browse code with it (and you'll also see that it can show the C-implementation of a class):

    > pry
    pry(main)> show-
    show-command  show-doc      show-input    show-method   show-source
    pry(main)> show-source Array
    
    From: object.c in Ruby Core (C Method):
    Number of lines: 6
    
    static VALUE
    rb_f_array(obj, arg)
        VALUE obj, arg;
    {
        return rb_Array(arg);
    }
    pry(main)> cd Array
    pry(Array):1> show-source each
    
    From: array.c in Ruby Core (C Method):
    Number of lines: 12
    
    VALUE
    rb_ary_each(ary)
        VALUE ary;
    {
        long i;
    
        RETURN_ENUMERATOR(ary, 0, 0);
        for (i=0; i<RARRAY(ary)->len; i++) {
        rb_yield(RARRAY(ary)->ptr[i]);
        }
        return ary;
    }
    pry(Array):1>
    

    Pry can of course also list the Ruby source of classes.

    Another useful tool for browsing the C-source for Ruby is the Ruby code cross reference:
    http://rxr.whitequark.org/

    However right now it seems to be down, but hopefully it will be up again soon.