Reading docs in irb
Asked Answered
X

3

8

One thing I miss about ipython is it has a ? operator which diggs up the docs for a particular function.

I know ruby has a similar command line tool but it is extremely inconvenient to call it while I am in irb.

Does ruby/irb have anything similar?

Xanthophyll answered 12/8, 2011 at 6:18 Comment(0)
A
8

Pry is a Ruby version of IPython, it supports the ? command to look up documentation on methods, but uses a slightly different syntax:

pry(main)> ? File.dirname

From: file.c in Ruby Core (C Method):
Number of lines: 6

visibility:  public
signature:  dirname()

Returns all components of the filename given in file_name
except the last one. The filename must be formed using forward
slashes (/'') regardless of the separator used on the
local file system.

   File.dirname("/home/gumby/work/ruby.rb")   #=> "/home/gumby/work"

You can also look up sourcecode with the $ command:

pry(main)> $ File.link

From: file.c in Ruby Core (C Method):
Number of lines: 14

static VALUE
rb_file_s_link(VALUE klass, VALUE from, VALUE to)
{
    rb_secure(2);
    FilePathValue(from);
    FilePathValue(to);
    from = rb_str_encode_ospath(from);
    to = rb_str_encode_ospath(to);

    if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
    sys_fail2(from, to);
    }
    return INT2FIX(0);
}

See http://pry.github.com for more information :)

Alinealinna answered 14/8, 2011 at 11:45 Comment(2)
Thanks! That's what I really needed!Xanthophyll
Is it possible to include some minimal instruction on how to get to the pry prompt (for noobies)? E.g. install pry and pry-doc gem install pry && gem install pry-doc, require them both, then inside IRB run the command: pry, and only then try the code in the answer. I feel like your assumption that people will know this is pretty sound, but it might help for noobies like me to have those first few pointers there tooCanto
U
6

You can start with

irb(main):001:0> `ri Object`

Although the output of this is less than readable. You'd need to filter out some metacharacters.

In fact, someone already made a gem for it

gem install ori

Then in irb

irb(main):001:0> require 'ori'
=> true
irb(main):002:0> Object.ri
Looking up topics [Object] o
= Object < BasicObject

------------------------------------------------------------------------------
= Includes:
Java (from gem activesupport-3.0.9)

(from gem activesupport-3.0.9) [...]
Undue answered 12/8, 2011 at 7:5 Comment(1)
+1 for including a simple, practical solution in your answer!Recondition
H
3

No, it doesn't. Python has docstrings:

def my_method(arg1,arg2):
  """ What's inside this string will be made available as the __doc__ attribute """
  # some code

So, when the ? is called from ipython, it probably calls the __doc__ attribute on the object. Ruby doesn't have this.

Hardily answered 12/8, 2011 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.