In Python, you can access an object's docstring by using obj.__doc__
. What is the equivalent action in Ruby?
What is the equivalent of a Python docstring in Ruby?
19.3k views Asked by parzival AtThere are 5 answers
It's easier to document in Ruby using Yard, which supports different tags like :NODOC:
To document your code with Yard, just write the comment above your code.
# MyClass.new(...) some comment here
class MyClass
end
# foo("bar")
def foo(bar = nil)
end
then run yard
on the current working directory of your project, this will generate the $PWD/doc
directory for you with a nice set of documentations.
Ruby has named HEREDOCS
that support various formatting options such as literal, leading whitespace, and others. Two useful articles I found on this are:
Below are some quick examples:
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
also support string interpolation.
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
Unfortunatelly Ruby does not have any Python like built-in docstrings.
RDoc looks terrible. RDoc is designed to be processed into HTML format and read in the we browser. It's not plain text. Who likes reading HTML-like source code? YARD is better. There is also TomDoc which use just plain text. But none of them compare to Pythonic docstrings which e.g. allow for simple autocompletion from any python console and do need to use any processing tool.
Ruby does not have a Python
__doc__
equivalent. They often use Rdoc Format for documentation, for example: