Ruby中的Python文档字符串的等价物是什么?

hrysbysz  于 2023-06-29  发布在  Ruby
关注(0)|答案(5)|浏览(172)

在Python中,可以使用obj.__doc__访问对象的文档字符串。Ruby中的等效操作是什么?

esyap4oy

esyap4oy1#

Ruby没有Python __doc__的等价物。他们经常使用Rdoc Format作为文档,例如:

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

  # A vertical position.
  def y
  end
end
p1tboqfb

p1tboqfb2#

不幸的是,Ruby没有任何类似Python的内置文档字符串。
RDoc看起来很糟糕。RDoc被设计成HTML格式并在浏览器中读取。这不是纯文本。谁喜欢阅读类似HTML的源代码?院子更好。还有TomDoc,它只使用纯文本。但是它们都不能与Pythonic文档字符串相比,例如。允许从任何python控制台进行简单的自动完成,并且需要使用任何处理工具。

q0qdq0h2

q0qdq0h23#

使用Yard在Ruby中编写文档更容易,它支持不同的标记,如:NODOC:
要使用Yard记录您的代码,只需在代码上方写入注解。

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

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

然后在你的项目的当前工作目录下运行yard,这将为你生成一个$PWD/doc目录,里面有一组很好的文档。

gxwragnw

gxwragnw4#

我不相信露比支持这个。

gz5pxeao

gz5pxeao5#

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

相关问题