How can I comment multiple lines in Ruby?
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
:
=begin
= begin
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.
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.
=begin
comment line 1
comment line 2
=end
make sure =begin and =end is the first thing on that line (no spaces)
=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.
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.