如何在Ruby中注释多行?
当前回答
=begin
(some code here)
=end
and
# This code
# on multiple lines
# is commented out
都是正确的。第一种注释类型的优点是可编辑性,因为删除的字符更少,所以取消注释更容易。第二类注释的优点是逐行读取代码的可读性,更容易判断某一行已被注释掉。你的电话,但想想谁会来找你,他们阅读和维护起来有多容易。
其他回答
=begin
My
multiline
comment
here
=end
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引擎没有正确呈现语法着色。测试它如何在您选择的编辑器中呈现是一项练习
如果有人在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
comment line 1
comment line 2
=end
确保=beginand=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之间没有空格:
正确:=开始错误:=开始
推荐文章
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 在构建中编写注释的语法是什么?gradle文件?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- 在Gem::Specification.reset期间未解决的规格:
- Delete_all vs destroy_all
- 双引号vs单引号
- 用any可以吗?'来检查数组是否为空?
- Rails获取“each”循环的索引
- Ruby类实例变量与类变量
- 在Ruby中输出数组到CSV