如何在Ruby中注释多行?
#1楼
=begin
(some code here)
=end
和
# This code
# on multiple lines
# is commented out
都是正确的。 第一种类型的注释的优点是可编辑性,因为删除了较少的字符,因此更易于取消注释。 第二种注释的优点是可读性-逐行读取代码,更容易分辨出已注释掉特定的一行。 您打来的电话,但请考虑谁在追随您,以及他们阅读和维护它们有多容易。
#2楼
使用以下任一方法:
=begin This is a comment block =end
要么
# This # is # a # comment # block
是rdoc当前支持的仅有两个,这是仅使用我认为的这些的一个很好的理由。
#3楼
这是一个例子:
=begin
print "Give me a number:"
number = gets.chomp.to_f
total = number * 10
puts "The total value is : #{total}"
=end
介于=begin
和=end
之间的所有内容都将被视为注释,无论其之间包含多少行代码。
注意:确保=
和begin
之间没有空格:
- 正确:
=begin
- 错误:
= begin
#4楼
=begin
My
multiline
comment
here
=end
#5楼
#!/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!"
#6楼
#!/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.
- 这就是它的外观(通过屏幕截图)-否则很难解释以上注释的外观。 点击放大 :
#7楼
尽管存在=begin
和=end
,但是注释的常规且更正确的方法是在每行上使用#
。 如果您阅读任何ruby库的源代码,您将发现这几乎是在所有情况下进行多行注释的方式。
#8楼
如果有人在Ruby on Rails中寻找在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 %>
这将起作用。
#9楼
=begin comment line 1 comment line 2 =end
确保= begin和= end是该行的第一件事(无空格)
#10楼
我不确定它的工作方式,但是您可以在要注释的代码的开头和结尾加上斜杠
码
puts "hello"
/
puts "world"
/
puts "peace"
输出值
hello
peace