Multi-Line Comments in Ruby?

2019-01-08 02:56发布

How can I comment multiple lines in Ruby?

标签: ruby comments
9条回答
贼婆χ
2楼-- · 2019-01-08 03:05

Using either:

=begin
This
is
a
comment
block
=end

or

# This
# is
# a
# comment
# block

are the only two currently supported by rdoc, which is a good reason to use only these I think.

查看更多
时光不老,我们不散
3楼-- · 2019-01-08 03:16
#!/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.
查看更多
神经病院院长
4楼-- · 2019-01-08 03:18
#!/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!"
查看更多
Viruses.
5楼-- · 2019-01-08 03:20
=begin
(some code here)
=end

and

# This code
# on multiple lines
# is commented out

are both correct. The advantage of the first type of comment is editability—it's easier to uncomment because fewer characters are deleted. The advantage of the second type of comment is readability—reading the code line by line, it's much easier to tell that a particular line has been commented out. Your call but think about who's coming after you and how easy it is for them to read and maintain.

查看更多
倾城 Initia
6楼-- · 2019-01-08 03:21

=begin comment line 1 comment line 2 =end make sure =begin and =end is the first thing on that line (no spaces)

查看更多
仙女界的扛把子
7楼-- · 2019-01-08 03:21

In case someone is looking for a way to comment multiple lines in a html template in Ruby on Rails, there might be a problem with =begin =end, for instance:

<%
=begin
%>
  ... multiple HTML lines to comment out
  <%= image_tag("image.jpg") %>
<%
=end
%>

will fail because of the %> closing the image_tag.

In this case, maybe it is arguable whether this is commenting out or not, but I prefer to enclose the undesired section with an "if false" block:

<% if false %>
  ... multiple HTML lines to comment out
  <%= image_tag("image.jpg") %>
<% end %>

This will work.

查看更多
登录 后发表回答