Comments are simply information added to a program’s source code for documentation purposes. Language interpreters and compilers ignore comments. Although the main use of comments is to document and describe the operations of a block of code, they can be convenient when debugging your code.
In this tutorial, we will learn various ways of commenting code in Ruby scripts.
Basic Usage: Single Line Comments
There are various types of comments in Ruby. However, the most basic one is a single line comment.
It starts with a pound symbol (#) and continues to the end of the line.
print "Hello from Ruby!"
As you can see in the above example, the single line comment starts with the pound symbol and spans to the end of the line.
The Ruby Interpreter ignores the text inside the single line comment, even if it carries valid Ruby code.
A single line comment in Ruby can start at the beginning of a line or the end, as shown below:
In this case, the content before the pound (#) sign is counted as valid Ruby code while the content after that is not.
In other cases, you need to describe what the code does in a more detailed fashion. To include comments that span multiple lines in Ruby, we implement block comments.
There are two ways to implement block comments in Ruby:
This method uses the =begin and =end format to enclose the lines inside the block as comments.
Here is an example:
This is a comment
that spans multiple lines
and its very useful for detailed documentation
print "Hi Block comments!"
In this type of comment, we start by using the =begin keyword followed by all the lines we wish to comment on and close with =end.
Usage of this comment format is rare because it does not offer much flexibility in the formatting of the comments, and it’s very unreadable.
2: Multiple Pound Symbols (#)
The most common way of commenting multiple lines in Ruby is to pre-append each line with a pound sign.
Here is an example:
# that spans multiple lines
# and it's very useful for detailed documentation
In this case, we have multiple lines commented out. Using modern editors, you can highlight a block of code and comment it out at once.
Comments & Magic Comments
Ruby is an interesting language because it offers magic comments. Magic comments take a format similar to regular comments, but instead of being ignored by the interpreter, they change the interpreter’s behavior.
Magic comments contain Ruby directives that define what to modify about the interpreter.
The example below shows a magic comment to modify the encoding for string literals.
Although the above looks similar to a regular comment, it contains a Ruby-recognized directive.
To learn more about Magic comment directives, consider the Ruby Comments Documentation.
This quick guide discussed various types of Ruby comments, including how to implement them with ease.