How to utilize comments in Ruby programming language
We will explore the utilization of comments in Ruby programs for making notes, as well as leveraging them as a debugging tool.
Syntax and usage of comments
In Ruby, comments start with a hash mark (#) and extend till the end of the line, as shown below:
# This is a comment in Ruby
Although it is not mandatory, it is recommended to add a space after the hash symbol to enhance the readability of the comment.
When running a program, comments in the code are completely ignored by the Ruby interpreter, therefore, no indication of them will be visible. Comments serve the purpose of aiding humans in understanding the source code rather than being executed by computers.
In a basic Ruby program, such as the one demonstrated in the tutorial How to Write Your First Ruby Program, you have the option to utilize comments to provide further explanation of the actions taking place in each segment of the code.
# Display a prompt to the user
puts "Please enter your name."
# Save the input they type and remove the last character (the enter keypress)
name = gets.chop
# Print the output to the screen
puts "Hi, #{name}! I'm Ruby!"
These remarks provide an overall understanding of the program’s different sections and their functionalities.
In a program that loops through an array and shows its contents in the form of an HTML list, you may come across explanatory comments that provide additional information about the code’s function.
sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']
# transform each entry in the array to an HTML entity, with leading spaces and a newline.
listitems = sharks.map{ |shark| " <li>#{shark}</li>\n"}
# Print the opening <ul>, then print the array of list items
print "<ul>\n#{listitems.join}</ul>"
You might not have experience with functions like map and join yet, but by reading the comments, you can understand how this program functions and how the result may appear. Give it a try. Copy this code into a file called sharks.rb and execute it.
- ruby sharks.rb
You will observe the output of the program.
<ul> <li>hammerhead</li> <li>great white</li> <li>dogfish</li> <li>frilled</li> <li>bullhead</li> <li>requiem</li> </ul>
You may have observed that the comments are not visible as the interpreter has disregarded them. However, it is likely that the output met your anticipated outcome. Comments hold significant value as a means of communication, particularly when the reader is unfamiliar with the language.
Comments should be aligned with the corresponding code by maintaining the same level of indentation. For instance, a class definition with no indentation would have an uncommented line at the same indentation level, and each subsequent level of indentation would have aligned comments for the relevant code.
Here is a Ruby program that simulates a Magic 8-Ball game. When you ask a question, the computer will provide a random answer. You can observe that the comments in each section are formatted with the same level of indentation as the code.
# The Eightball class represents the Magic 8-Ball.
class Eightball
# Set up the available choices
def initialize
@choices = ["Yes", "No", "All signs point to yes", "Ask again later", "Don't bet on it"]
end
# Select a random choice from the available choices
def shake
@choices.sample
end
end
def play
puts "Ask the Magic 8 Ball your question."
# Since we don't need their answer, we won't capture it.
gets
# Create a new instance of the Magic 8 Ball and use it to get an answer.
eightball = Eightball.new
answer = eightball.shake
puts answer
# Prompt to restart the game and evaluate the answer.
puts "Want to try again? Press 'y' to continue or any other key to quit."
answer = gets.chop
if answer == 'y'
play
else
exit
end
end
# Start the first game.
play
Comments are meant to assist programmers, whether they are the original coder or others involved in using or working together on the project. Therefore, it is crucial to properly manage and update comments, treating them with the same importance as the code itself. A comment that contradicts the code is far more detrimental than not having a comment at all.
In the beginning, it’s common to write numerous comments to grasp the task at hand. However, as you become more skilled, the focus should shift towards using comments to clarify the reasoning behind the code rather than its specifics or implementation. Unless the code is exceptionally complex, its functionality or methodology can typically be understood by examining it.
After gaining knowledge in Ruby, this type of comment becomes less valuable.
# print "Hello Horld" to the screen.
print "Hello World"
This comment repeats the functionality of the code, and although it has no impact on the program’s output, it adds unnecessary clutter when reading the code.
Block comments are useful for writing more detailed comments when necessary.
Comments that are used to explain or describe code and are visually separated from the rest of the code by special characters or symbols.
Block comments are employed to clarify intricate or unfamiliar code to the reader. These extended comments can be applied to a portion or the entirety of the subsequent code, and they are also indented at the same level as the code.
When writing block comments, start each line with a hash mark followed by a space for better legibility. To indicate multiple paragraphs, insert a single hash mark between them, separated by an empty line.
This block comment is an illustration from the source code of the Sinatra web framework. It offers additional information to fellow developers regarding the functionality of this specific code snippet.
Here is one possible paraphrase:
You can find the “sinatra” repository on GitHub at this URL: https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb
...
# Some Rack handlers (Thin, Rainbows!) implement an extended body object protocol, however,
# some middleware (namely Rack::Lint) will break it by not mirroring the methods in question.
# This middleware will detect an extended body object and will make sure it reaches the
# handler directly. We do this here, so our middleware and middleware set up by the app will
# still be able to run.
class ExtendedRack < Struct.new(:app)
def call(env)
result, callback = app.call(env), env['async.callback']
return result unless callback and async?(*result)
after_response { callback.call result }
setup_close(env, *result)
throw :async
end
...
Block comments are highly useful when you require in-depth explanations for sections of code. Yet, it is advisable to minimize excessive commenting in your code to prevent redundancy and unnecessary clutter. Unless you are targeting a specific group of programmers, it is better to assume that others can comprehend the Ruby code without excessive comments. The purpose of comments should be to provide context, rather than repeating the code itself.
Ruby has a seldom-used alternative syntax for multi-line comments. Here’s an instance:
=begin
This is a multi-line comment.
You can use this approach to make your comments
span multiple lines without placing hash marks at the start of each
line.
=end
The =begin and =end lines should always start at the beginning of the line, without any indentation. This is the reason why you won’t frequently come across this being utilized.
Next, we will examine inline comments.
Comments that are included directly within a code or text document.
Inline comments appear on the identical line as a statement and come after the code. Similar to other comments, they commence with a hash symbol, followed by a space to enhance readability.
Typically, inline comments are presented in this manner.
[code] # Inline comment about the code
Using inline comments should be done in moderation, but they can be helpful in clarifying complex or less apparent sections of the code. They might also come in handy if you anticipate forgetting a line of code in the future or when collaborating with someone who may not be well-versed in certain aspects of the code.
If, for instance, you do not frequently utilize mathematical operations in your Ruby programs, it is possible that either you or those you cooperate with might be unaware that the given code generates a complex number. Hence, it would be advisable to add a comment directly within the code to clarify this.
a=Complex(4,3) # Create the complex number 4+3i
You can utilize inline comments to provide an explanation for a particular action.
pi = 3.14159 # Intentionally limiting the value of pi for this program.
Only add comments in the code when it is necessary and can offer useful guidance for the reader.
Writing comments in the code to facilitate testing purposes.
Apart from using comments for code documentation, you may also employ the hash mark to exclude code execution while testing or debugging your program. Occasionally, when encountering errors after adding new code lines, it can be helpful to comment out specific lines to narrow down and resolve the issue.
One option for paraphrasing the given statement could be:
For instance, in the Magic 8-Ball game, you may wish to avoid the game running again if your sole concern is to verify the accuracy of the answer through the code evaluation. In such a case, you can simply deactivate the line of code responsible for initiating the game once more by adding a comment.
...
# Prompt to restart the game and evaluate the answer.
puts "Want to try again? Press 'y' to continue or any other key to quit."
answer = gets.chop
if answer == 'y'
# play
else
exit
end
end
...
When implementing a solution in your code, comments provide an opportunity to experiment with alternative options. For instance, when dealing with arrays in Ruby, you can utilize comments to test multiple approaches and ascertain the one that suits your preferences the best.
sharks = ["Tiger", "Great White", "Hammerhead"]
# for shark in sharks do
# puts shark
# end
sharks.each do |shark|
puts shark
end
By commenting out code, you can experiment with various programming techniques and also locate the origin of an error by systematically commenting out and executing sections of a program.
In conclusion
Including comments in your Ruby code enhances its readability for humans, including yourself in the future. By including relevant and useful comments, you facilitate collaboration with others on programming projects. Additionally, comments assist in comprehending your code when you revisit your project after a significant duration.
More tutorials
A guide on creating a Ruby on Rails application on Ubuntu 22.04.(Opens in a new browser tab)
one-click installation feature of Ruby on Rails on Silicon Cloud.(Opens in a new browser tab)
How to include items to a list in Python(Opens in a new browser tab)
Converting string to array in the Java programming language(Opens in a new browser tab)
Python HTTP requests such as GET and POST methods.(Opens in a new browser tab)