如何在Ruby中注释多行?
当前回答
def idle
<<~aid
This is some description of what idle does.
It does nothing actually, it's just here to show an example of multiline
documentation. Thus said, this is something that is more common in the
python community. That's an important point as it's good to also fit the
expectation of your community of work. Now, if you agree with your team to
go with a solution like this one for documenting your own base code, that's
fine: just discuss about it with them first.
Depending on your editor configuration, it won't be colored like a comment,
like those starting with a "#". But as any keyword can be used for wrapping
an heredoc, it is easy to spot anyway. One could even come with separated
words for different puposes, so selective extraction for different types of
documentation generation would be more practical. Depending on your editor,
you possibly could configure it to use the same syntax highlight used for
monoline comment when the keyword is one like aid or whatever you like.
Also note that the squiggly-heredoc, using "~", allow to position
the closing term with a level of indentation. That avoids to break the visual reading flow, unlike this far too long line.
aid
end
请注意,在本文发表的时候,stackoverflow引擎没有正确呈现语法着色。测试它如何在您选择的编辑器中呈现是一项练习
其他回答
尽管存在=begin和=end,但正常且更正确的注释方式是在每行上使用#。如果您阅读任何ruby库的源代码,您会发现几乎在所有情况下都是这样进行多行注释的。
=begin
(some code here)
=end
and
# This code
# on multiple lines
# is commented out
都是正确的。第一种注释类型的优点是可编辑性,因为删除的字符更少,所以取消注释更容易。第二类注释的优点是逐行读取代码的可读性,更容易判断某一行已被注释掉。你的电话,但想想谁会来找你,他们阅读和维护起来有多容易。
#!/usr/bin/env ruby
=begin
Every body mentioned this way
to have multiline comments.
The =begin and =end must be at the beginning of the line or
it will be a syntax error.
=end
puts "Hello world!"
<<-DOC
Also, you could create a docstring.
which...
DOC
puts "Hello world!"
"..is kinda ugly and creates
a String instance, but I know one guy
with a Smalltalk background, who
does this."
puts "Hello world!"
##
# most
# people
# do
# this
__END__
But all forgot there is another option.
Only at the end of a file, of course.
这就是它的样子(通过截图)——否则很难解释上面的评论会是什么样子。单击以放大:
使用以下任一项:
=begin This is a comment block =end
or
# This # is # a # comment # block
是rdoc目前唯一支持的两个,我认为这是一个很好的理由只使用这些。
#!/usr/bin/env ruby
=begin
Between =begin and =end, any number
of lines may be written. All of these
lines are ignored by the Ruby interpreter.
=end
puts "Hello world!"
推荐文章
- 如何找到包含匹配值的哈希键
- Android:垂直对齐多行EditText(文本区域)
- 如何在Rails中找到当前的路由?
- 在Ruby中->运算符叫什么?
- Rails参数解释?
- Ruby中DateTime和Time的区别
- 如何从代理服务器后面更新Ruby Gems (ISA-NTLM)
- 如何用另一个键替换哈希键
- attr_accessor和attr_accessible的区别
- 如何从Ruby文件路径中获得没有扩展名的文件名
- rvm安装失败:“rvm不是一个函数”
- 学习Ruby on Rails
- Ruby中的数组切片:解释不合逻辑的行为(摘自Rubykoans.com)
- 如何分割一个带分隔符的字符串在Ruby和转换为一个数组?
- Jenkins:注释可以添加到Jenkins文件中吗?