Ruby内联文档

2024-10-03 11:21:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在IRB或其他交互式解释器(如pry)中,如何获得关于对象和方法的内联文档?例如,我可以做到:

[1] pry(main)> x = 'hello world'
=> "hello world"
[2] pry(main)> x.st
x.start_with?  x.strip        x.strip!   
[2] pry(main)> x.st

但是现在我想阅读usage/interface/rdoc对这些方法及其接口的描述。顺便说一下,中间那条线是制表符补全。在

我在寻找类似于ipython的东西,其中可以将?附加到属性名以查看docstring,或者甚至可以添加一个??来查看源代码:

^{pr2}$

Tags: 对象方法文档helloworldmainwithusage
1条回答
网友
1楼 · 发布于 2024-10-03 11:21:27

首先需要安装

gem install pry-doc

然后可以使用show-doc [method]命令(别名为? [method])获取文档

^{pr2}$

您甚至可以使用show-source [method]命令(别名为$ [method])查看源代码

pry> show-source x.strip

From: string.c (C Method):
Owner: String
Visibility: public
Number of lines: 7

static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}

这个例子显示了C源代码,但是如果有Ruby源代码,它会显示实际的Ruby源代码。考虑这个简单的类:

pry> class Foo
pry*   def bar
pry*     puts 'hello'
pry*   end
pry* end
=> nil

你可以看看整个班级:

pry> show-source Foo

From: (pry) @ line 2:
Class name: Foo
Number of lines: 5

class Foo
  def bar
    puts 'hello'
  end
end

但也只是一种特定的方法:

pry> show-source Foo#bar

From: (pry) @ line 3:
Owner: Foo
Visibility: public
Number of lines: 3

def bar
  puts 'hello'
end

正如@banister建议的那样,您可以通过Pry.commands.command添加自定义命令。这样您就可以在~/.pryrc中定义???命令:

Pry.commands.command /(.+) \?\z/ do |a|
  run "show-doc", a
end

Pry.commands.command /(.+) \?\?\z/ do |a|
  run "show-source", a
end

注意,我们在方法和?之间需要一个空格,因为Ruby方法可能以?(例如Fixnum#zero?)结尾,这些方法将中断。一些例子:

pry> puts ?

From: io.c (C Method):
Owner: Kernel
Visibility: private
Signature: puts(*arg1)
Number of lines: 3

Equivalent to

    $stdout.puts(obj, ...)

pry> puts ??

From: io.c (C Method):
Owner: Kernel
Visibility: private
Number of lines: 8

static VALUE
rb_f_puts(int argc, VALUE *argv, VALUE recv)
{
    if (recv == rb_stdout) {
        return rb_io_puts(argc, argv, recv);
    }
    return rb_funcall2(rb_stdout, rb_intern("puts"), argc, argv);
}

pry> 0.zero?     # still works!
=> true

pry> 0.zero? ?

From: numeric.c (C Method):
Owner: Fixnum
Visibility: public
Signature: zero?()
Number of lines: 1

Returns true if fix is zero.

相关问题 更多 >