Multi-Line Comments in Ruby?

后端 未结 10 1624
忘了有多久
忘了有多久 2020-11-30 16:21

How can I comment multiple lines in Ruby?

相关标签:
10条回答
  • 2020-11-30 16:31

    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
    0 讨论(0)
  • 2020-11-30 16:36

    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.

    0 讨论(0)
  • 2020-11-30 16:37

    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.

    0 讨论(0)
  • 2020-11-30 16:47

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

    0 讨论(0)
  • 2020-11-30 16:48
    =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.

    0 讨论(0)
  • 2020-11-30 16:49

    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.

    0 讨论(0)
提交回复
热议问题