Python中的docstring在Ruby中有什么等价物?

48
在Ruby中,您可以通过使用obj.method(:method_name).super_method.source_location来访问对象的文档字符串。

8
也许你应该首先询问 Ruby 是否有文档字符串(docstrings)... - user395760
5个回答

27

Ruby没有Python中的__doc__的等效物。通常使用Rdoc格式进行文档编写,例如:

# For example, a square or circle.
class Shape
  # A horizontal position.
  def x
  end

  # A vertical position.
  def y
  end
end

所以,只是为了指出,这意味着你不能仅仅通过在解释器中使用print(len.__doc__)help(len)来查找某个方法的一些信息。你需要一个大型的外部工具来完成这个任务。 - xealits

5
很遗憾,Ruby没有任何类似Python内置文档字符串的功能。RDoc看起来很糟糕。RDoc被设计成可转换为HTML格式并在Web浏览器中阅读,而不是纯文本。谁喜欢阅读类似HTML的源代码呢?YARD更好一些。还有TomDoc,它只使用纯文本。但是,它们都无法与Pythonic docstrings相比,例如允许从任何Python控制台进行简单的自动完成并且不需要使用任何处理工具。

2

使用Yard在Ruby中编写文档更加容易,支持不同的标记,如:NODOC:

要使用Yard为您的代码编写文档,只需在代码上方写下注释即可。

# MyClass.new(...) some comment here
class MyClass
end

# foo("bar")
def foo(bar = nil)
end

然后在您的项目当前工作目录上运行yard,这将为您生成一个漂亮的文档集合,存储在$PWD/doc目录下。


4
院子(Yard)是一种可选的方式,然而Rdoc是标准的,因为它与Ruby一起提供。 - the Tin Man

2
我不相信 Ruby 支持这个功能。

0

Ruby 命名了HEREDOCS,支持各种格式选项,如字面意义、前导空白等。我找到的两篇有用的文章是:

以下是一些快速示例:

irb(main):001:0" puts <<~TILDE
irb(main):002:0"   This removes leading whitespace to the left
irb(main):003:0"     but preserves indentation underneath it,
irb(main):004:0"     which is quite helpful for formatting.
irb(main):005:0"
irb(main):006:0> TILDE
This removes leading whitespace to the left
  but preserves indentation underneath it,
  which is quite helpful for formatting.

irb(main):007:0" puts <<-LITERAL
irb(main):008:0"     This will do whatevery you
irb(main):009:0"    tell it to do
irb(main):010:0"         which can be nice if you want
irb(main):011:0"      things to be laid out very, very
irb(main):012:0"        p r e c i s e l y
irb(main):013:0"     ... except the problem is you have
irb(main):014:0"       to put this text all the way to the left
irb(main):015:0"     of your code if you want to avoid leading
irb(main):016:0"     whitespace.
irb(main):017:0> LITERAL
    This will do whatevery you
   tell it to do
        which can be nice if you want
     things to be laid out very, very
       p r e c i s e l y
    ... except the problem is you have
      to put this text all the way to the left
    of your code if you want to avoid leading
    whitespace.

HEREDOCS 也支持字符串内插。

irb(main):018:0> name = 'Jeff'
=> "Jeff"
irb(main):019:0" puts <<~INTERPOLATION
irb(main):020:0"   My name is #{name}
irb(main):021:0> INTERPOLATION
My name is Jeff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接