Ruby中的多行注释?

Moh*_*ain 728 ruby comments

如何在Ruby中注释多行?

Kon*_*ase 1322

#!/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.
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记`= begin`和`= end`不能以任何空格开头. (69认同)
  • 有趣的是,这个答案使语法高亮显示中的一些缺陷显而易见. (38认同)
  • 我更喜欢在它们之上使用`#`,主要是因为它在视觉上将注释行分隔得比`= begin` /`= end`或者使用here-to方法更好.而且,干得好. (26认同)
  • 并且在方法中不可能使用= begin = end (15认同)
  • 重要的是要注意,在上面的示例代码中,只有第一个`= begin ... = end`和最后一个块使用`#`在生成文档时被rdoc选中. (7认同)

Ada*_*ear 124

=begin
My 
multiline
comment
here
=end
Run Code Online (Sandbox Code Playgroud)

  • 我发现,如果我在= begin或= end之前添加了一个标签,则评论不起作用.= begin和= end每个都需要写在每行的开头. (53认同)
  • 当然,你*可以*做到这一点.有用.这非常罕见.我发现它很难看.也许我被困在我的方式? (4认同)

Rei*_*chs 54

尽管存在=begin=end,正常和更正确的评论方式是#在每一行使用's.如果您阅读任何ruby库的源代码,您会发现这几乎是所有情况下多线注释的完成方式.

  • 当然,有很多"有效"的方式来撰写评论.让我们在这里实用.如果您实际编写Ruby并阅读其他人编写的内容,那么您应该使用`#` comments.(我很困惑为什么这有两个downvotes.我猜Stack Overflow社区有时候会弄错!) (6认同)
  • 你可能会得到关于你的陈述中"更正确"部分的论据,因为它们都是有效的.我更喜欢使用`#`,因为它更明显.在评论代码时,重要的是要明确发生了什么.如果您在使用`= begin/= end`的编辑器中查看代码而没有代码着色的好处,则很难弄清楚为什么代码被忽略. (4认同)
  • `3 == three`其中`def三; 1 + 1 + 1结束.因此两者都有效.谁在乎?使用`3`! (4认同)
  • 这实际上并不是他问题的答案,因此投了反对票。 (2认同)

mik*_*iku 19

#!/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!"
Run Code Online (Sandbox Code Playgroud)

  • @ParthianShot - 这不是一件事 - 如果不在行的开头,则忽略= begin和= end.嵌套似乎不可能. (2认同)

the*_*Man 16

使用:

=begin
This
is
a
comment
block
=end

要么

# This
# is
# a
# comment
# block

是rdoc目前唯一支持的两个,这是我认为只使用这些的一个很好的理由.


La-*_*eja 13

=begin
(some code here)
=end
Run Code Online (Sandbox Code Playgroud)

# This code
# on multiple lines
# is commented out
Run Code Online (Sandbox Code Playgroud)

都是正确的.第一种评论的优点是可编辑性 - 它更容易取消注释,因为删除的字符越少.第二种注释的优点是可读性 - 逐行读取代码,更容易判断特定行已被注释掉.你的电话,但想想谁跟你在一起,以及他们阅读和维护是多么容易.


Pra*_*thi 12

这是一个例子:

=begin 
print "Give me a number:"
number = gets.chomp.to_f

total = number * 10
puts  "The total value is : #{total}"

=end
Run Code Online (Sandbox Code Playgroud)

所有你放在间=begin=end会的代码有多少行包含之间无论视为注释.

注意:确保=和之间没有空格begin:

  • 正确: =begin
  • 错误: = begin


ana*_*han 7

=begin
comment line 1
comment line 2
=end
Run Code Online (Sandbox Code Playgroud)

确保=begin并且=end是该行的第一件事(没有空格)