How can I comment multiple lines in Ruby?
问题:
回答1:
#!/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.
回答2:
=begin
My
multiline
comment
here
=end
回答3:
Despite the existence of =begin
and =end
, the normal and a more correct way to comment is to use #
's on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.
回答4:
#!/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!"
回答5:
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.
回答6:
=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.
回答7:
Here is an example :
=begin
print "Give me a number:"
number = gets.chomp.to_f
total = number * 10
puts "The total value is : #{total}"
=end
Everything you place in between =begin
and =end
will be treated as a comment regardless of how many lines of code it contains between.
Note: Make sure there is no space between =
and begin
:
- Correct:
=begin
- Wrong:
= begin
回答8:
=begin
comment line 1
comment line 2
=end
make sure =begin and =end is the first thing on that line (no spaces)
回答9:
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.