如何在Ruby中注释多行?
当前回答
#!/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和=end,但正常且更正确的注释方式是在每行上使用#。如果您阅读任何ruby库的源代码,您会发现几乎在所有情况下都是这样进行多行注释的。
如果有人在RubyonRails中寻找在html模板中注释多行的方法,那么=begin=end可能会有问题,例如:
<%
=begin
%>
... multiple HTML lines to comment out
<%= image_tag("image.jpg") %>
<%
=end
%>
将失败,因为%>正在关闭image_tag。
在这种情况下,这是否是注释掉可能是有争议的,但我更喜欢用“if false”块括住不需要的部分:
<% if false %>
... multiple HTML lines to comment out
<%= image_tag("image.jpg") %>
<% end %>
这会奏效的。
下面是一个示例:
=begin
print "Give me a number:"
number = gets.chomp.to_f
total = number * 10
puts "The total value is : #{total}"
=end
放置在=begin和=end之间的所有内容都将被视为注释,而不管其间包含多少行代码。
注意:确保=和begin之间没有空格:
正确:=开始错误:=开始
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 This is a comment block =end
or
# This # is # a # comment # block
是rdoc目前唯一支持的两个,我认为这是一个很好的理由只使用这些。
推荐文章
- Rails中的OO设计:在哪里放置东西
- 给定一个类,查看实例是否有方法(Ruby)
- 在日历应用程序中建模重复事件的最佳方法是什么?
- 如何创建一个私有类方法?
- 无法安装pg gem
- 双* (splat)操作符做什么
- 如何使用Ruby on Rails进行HTTP请求?
- TypeScript注释的语法记录在哪里?
- 如何从rake任务中提前返回?
- 什么&。(&点)在Ruby中是什么意思?
- 是什么阻碍了Ruby和Python获得V8的Javascript速度?
- CSV文件可以有注释吗?
- 运行pod设置给我“坏的解释器:没有这样的文件或目录”错误
- 在Ubuntu上安装sqlite3-ruby错误
- Ruby有什么Python没有的,反之亦然?