首页 文章

Ruby中的多行注释?

提问于
浏览
670

如何在Ruby中注释多行?

9 回答

  • 115

    使用:

    =begin
    This
    is
    a
    comment
    block
    =end
    

    要么

    # This
    # is
    # a
    # comment
    # block
    

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

  • 14

    如果有人正在寻找一种方法来在Ruby on Rails中的html模板中注释多行,那么= begin = end可能存在问题,例如:

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

    因为%>关闭image_tag而失败 .

    在这种情况下,也许这是否可以论证是否有评论,但我更喜欢用“if false”块封闭不需要的部分:

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

    这会奏效 .

  • 2

    =begin comment line 1 comment line 2 =end 确保= begin和= end是该行的第一件事(没有空格)

  • 13
    #!/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!"
    
  • 1

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

  • 52
    #!/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.
    
  • 1236
    =begin
    (some code here)
    =end
    

    # This code
    # on multiple lines
    # is commented out
    

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

  • 12

    这是一个例子:

    =begin 
    print "Give me a number:"
    number = gets.chomp.to_f
    
    total = number * 10
    puts  "The total value is : #{total}"
    
    =end
    

    您放在 =begin=end 之间的所有内容都将被视为注释,无论它包含多少行代码 .

    Note: 确保 =begin 之间没有空格:

    • 正确: =begin

    • 错误: = begin

  • 19
    =begin
    My 
    multiline
    comment
    here
    =end
    

相关问题