如何在 Ruby 中使用注释

介绍

评论是计算机程序中被编译者和解释者忽略的行。你可以使用评论来使你的程序更容易被其他程序员理解,通过使用它们来提供更多的背景或解释一个程序的每个部分正在做什么。

有些评论可能会永远留在代码中,例如解释背景的评论,而其他评论可能是暂时的,例如在构建程序时留下的笔记。

让我们来看看如何在Ruby程序中使用评论留下笔记,以及如何将其用作调试工具。

评论语法和使用

Ruby 中的评论以一个哈希标记(#)开始,并继续到行结束,如下:

1# This is a comment in Ruby

虽然不需要,但您应该在哈希标记后放置一个空白空间,以提高评论的可读性。

当你运行一个程序时,你不会在代码中看到任何评论的迹象;Ruby解释器完全忽略了它们。

在一个简单的Ruby程序中,如教程中(How to Write Your First Ruby Program)中的程序,你可以使用评论来提供有关代码的每个部分发生的事情的额外细节:

1[label greetings.rb]
2# Display a prompt to the user
3puts "Please enter your name."
4
5# Save the input they type and remove the last character (the enter keypress)
6name = gets.chop
7
8# Print the output to the screen
9puts "Hi, #{name}! I'm Ruby!"

这些评论给你一个一般的想法,该程序的每个部分做什么,以及它是如何工作的。

在对数组进行迭代并将其内容显示为HTML列表的程序中,您可能会看到这样的评论,这些评论对代码的作用有更多的解释:

1[label sharks.rb]
2sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']
3
4# transform each entry in the array to an HTML entity, with leading spaces and a newline.
5listitems = sharks.map{ |shark| " <li>#{shark}</li>\n"}
6
7# Print the opening <ul>, then print the array of list items
8print "<ul>\n#{listitems.join}</ul>"

您可能还不熟悉地图加入,但评论会给你一个想法,这个程序应该如何工作,输出可能是什么样子。

1ruby sharks.rb

您将看到该计划的结果:

1[secondary_label Output]
2<ul>
3<li>hammerhead</li>
4<li>great white</li>
5<li>dogfish</li>
6<li>frilled</li>
7<li>bullhead</li>
8<li>requiem</li>
9</ul>

请注意,您没有看到评论,因为翻译员忽略了评论,但输出可能与您所期望的相匹配。

也就是说,没有注释的类定义将有一个注释的注释,没有注释的评论,然后每个注释级别将有注释,这些注释与它注释的代码一致。

例如,这里是 Magic 8-Ball游戏的 Ruby 实现. 计算机将随机回答您提问。

 1[label magic8ball.rb]
 2# The Eightball class represents the Magic 8-Ball.
 3class Eightball
 4
 5# Set up the available choices
 6def initialize
 7@choices = ["Yes", "No", "All signs point to yes", "Ask again later", "Don't bet on it"]
 8end
 9
10# Select a random choice from the available choices
11def shake
12@choices.sample
13end
14end
15
16def play
17puts "Ask the Magic 8 Ball your question."
18
19# Since we don't need their answer, we won't capture it.
20gets
21
22# Create a new instance of the Magic 8 Ball and use it to get an answer.
23eightball = Eightball.new
24answer = eightball.shake
25puts answer
26
27# Prompt to restart the game and evaluate the answer.
28puts "Want to try again? Press 'y' to continue or any other key to quit."
29answer = gets.chop
30
31if answer == 'y'
32play
33else
34exit
35end
36end
37
38# Start the first game.
39play

评论应该有助于程序员,无论是原始程序员还是其他使用或协作项目的人,这意味着评论必须像代码一样保持。

当你刚刚开始时,你可能会写很多评论来帮助你理解你正在做什么,但随着你获得更多的经验,你应该寻求使用评论来解释代码背后的 why 而不是 whathow

例如,此类评论一旦你了解Ruby,就不会那么有用:

1# print "Hello Horld" to the screen.
2print "Hello World"

此评论重申了代码已经做了什么,虽然它不会影响程序的输出,但当您阅读代码时会产生额外的噪音。

有时你需要写一些更详细的评论,这就是区块链评论的用途。

区块链评论

您可以使用区块评论来解释更复杂的代码或代码,您不希望读者熟悉。

在区块评论中,每个行都以哈希标记开始,然后是单个可读空间,如果需要使用多个段落,它们应该由包含单个哈希标记的行分开。

以下是从 Sinatra Web 框架的源代码中进行的块评论的例子,它为其他开发人员提供了有关该特定代码如何工作的某些背景:

 1[label https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb]
 2...
 3# Some Rack handlers (Thin, Rainbows!) implement an extended body object protocol, however,
 4# some middleware (namely Rack::Lint) will break it by not mirroring the methods in question.
 5# This middleware will detect an extended body object and will make sure it reaches the
 6# handler directly. We do this here, so our middleware and middleware set up by the app will
 7# still be able to run.
 8class ExtendedRack < Struct.new(:app)
 9def call(env)
10result, callback = app.call(env), env['async.callback']
11return result unless callback and async?(*result)
12after_response { callback.call result }
13setup_close(env, *result)
14throw :async
15end
16...

当你需要彻底解释代码时,区块链评论非常好,但是,你应该尽量避免过度评论你的代码,因为这些评论可能会多余,并产生额外的噪音。

Ruby 具有用于多行评论的替代语法,但很少使用。

1[label multiline.rb]
2=begin
3This is a multi-line comment.
4You can use this approach to make your comments
5span multiple lines without placing hash marks at the start of each
6line.
7=end

=開始=結束的行必須在行開始. 它們不能被插入. 這就是為什麼你很少看到這個使用。

让我们来看看下面的内线评论。

内地评论

与其他评论一样,它们以哈希标记开始,然后是单个白空间字符以便可读性。

一般来说,内部评论看起来像这样:

1[code] # Inline comment about the code

内线评论应该谨慎使用,但可以有效地解释代码的复杂或不显而易见部分,如果您认为您可能不记得未来写的代码的一行,或者如果您正在与你知道可能不熟悉代码的所有方面的人合作,它们也可能有用。

例如,如果您在 Ruby 程式中不使用大量數學,您或您的合作者可能不知道下列數字會產生複雜的數字,因此您可能想要包含關於此的內線評論:

1a=Complex(4,3) # Create the complex number 4+3i

您还可以使用内线评论来解释做某事的原因:

1pi = 3.14159 # Intentionally limiting the value of pi for this program.

在线发表的评论只应在必要时使用,并且可以为阅读程序的人提供有用的指导。

评论出测试代码

除了使用评论作为文档代码的方式外,您还可以使用哈希标记来评论您在测试或调试您目前正在创建的程序时不想执行的代码。

例如,在魔法8球游戏中,你可能想阻止游戏再次运行,因为你只是想确保代码正确评估答案。

 1[label 8ball.rb]
 2...
 3
 4# Prompt to restart the game and evaluate the answer.
 5puts "Want to try again? Press 'y' to continue or any other key to quit."
 6answer = gets.chop
 7
 8if answer == 'y'
 9# play
10else
11exit
12end
13end
14...

评论还允许您在确定如何在代码中实现解决方案时尝试替代方案,例如,您在 Ruby 中使用数组时可能想要尝试几种不同的方法。

 1[label sharks.rb]
 2sharks = ["Tiger", "Great White", "Hammerhead"]
 3
 4# for shark in sharks do
 5# puts shark
 6# end
 7
 8sharks.each do |shark|
 9puts shark
10end

评论代码允许您尝试不同的编程方法,并通过系统地评论和运行程序部分来帮助您找到错误的来源。

结论

使用 Ruby 程序中的评论可以使程序更易于读取,包括你未来的自我。包括相关和有用的适当评论,使其他人更容易与你在编程项目上合作。

Published At
Categories with 技术
Tagged with
comments powered by Disqus