在Ruby中,您可以通过使用
obj.method(:method_name).super_method.source_location
来访问对象的文档字符串。obj.method(:method_name).super_method.source_location
来访问对象的文档字符串。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使用Yard在Ruby中编写文档更加容易,支持不同的标记,如:NODOC:
要使用Yard为您的代码编写文档,只需在代码上方写下注释即可。
# MyClass.new(...) some comment here
class MyClass
end
# foo("bar")
def foo(bar = nil)
end
然后在您的项目当前工作目录上运行yard
,这将为您生成一个漂亮的文档集合,存储在$PWD/doc
目录下。
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