如何以编程方式获取corelib / stdlib的ruby文档?

时间:2014-08-08 10:59:17

标签: ruby

我有一个大阵容。这个数组的所有ruby stdlib都是这样的格式:

Array#size
Array#push
String#replace
String#<<

等等。现在我希望找到该方法的相应文档 并将其交还给用户。 (它就像一个便宜的REPL,如果你是一个迷你irb 所以 - 我只需要这个迷你功能,没有完全成熟。)

我怎样才能找到记录Array#push的部分? 我很好用rdoc / yard / ri,我只需要得到 来自那里的文件以字符串形式。

2 个答案:

答案 0 :(得分:2)

您可以深入研究RDoc文档并访问ri使用的Rdoc::RI::Driver代码,然后播放一些游戏,了解它如何输出数据以捕获通常使用StringIO对象:

require 'rdoc'
require 'stringio'

ri = RDoc::RI::Driver.new(RDoc::RI::Driver.process_args(%w[-T --format=ansi ]))
ri.use_stdout = true

ri_output = ''
$stdout = StringIO.new(ri_output)
ri.display_method('Array#push') 
$stdout = STDOUT

puts ri_output

结果是:

[0m[1;32mArray#push[m

(from ruby core)
------------------------------------------------------------------------------
  ary.push(obj, ... )   -> ary

------------------------------------------------------------------------------

Append --- Pushes the given object(s) on to the end of this array. This
expression returns the array itself, so several appends may be chained
together. See also Array#pop for the opposite effect.

  a = [ "a", "b", "c" ]
  a.push("d", "e", "f")
          #=> ["a", "b", "c", "d", "e", "f"]
  [1, 2, 3,].push(4).push(5)
          #=> [1, 2, 3, 4, 5]

将输出类型更改为markdown以获得不使用ANSI终端显示代码的输出:

ri = RDoc::RI::Driver.new(RDoc::RI::Driver.process_args(%w[-T --format=markdown ]))

结果是:

# Array#push

(from ruby core)
---
    ary.push(obj, ... )   -> ary

---

Append --- Pushes the given object(s) on to the end of this array. This
expression returns the array itself, so several appends may be chained
together. See also Array#pop for the opposite effect.

    a = [ "a", "b", "c" ]
    a.push("d", "e", "f")
            #=> ["a", "b", "c", "d", "e", "f"]
    [1, 2, 3,].push(4).push(5)
            #=> [1, 2, 3, 4, 5]

这个小小的魔法允许我们捕获将在控制台上的STDOUT转换为字符串的正常输出:

ri_output = ''
$stdout = StringIO.new(ri_output)

此时,所有基于STDOUT的正常输出都将存储在ri_output中,而不会转到控制台。接下来,将STDOUT重新分配回$stdout非常重要,以便puts输出再次转到控制台:

$stdout = STDOUT

它可能在输出到正常的ri控制台输出之前拦截输出,但我没有看到一种方法或方法来做那个突出的方法。

答案 1 :(得分:1)

我会在系统调用中使用ri。例如

`ri Array#push`

返回

= Array#push

(from ruby core)
------------------------------------------------------------------------------
  ary.push(obj, ... )   -> ary

------------------------------------------------------------------------------

Append --- Pushes the given object(s) on to the end of this array. This
expression returns the array itself, so several appends may be chained
together. See also Array#pop for the opposite effect.

  a = [ "a", "b", "c" ]
  a.push("d", "e", "f")
          #=> ["a", "b", "c", "d", "e", "f"]
  [1, 2, 3,].push(4).push(5)
          #=> [1, 2, 3, 4, 5]