The different ways of using comments in Ruby
Published on 16-01-2022
Comments are notes and annotations in your Ruby code intended to be read by other programmers or your future self, that are ignored by the Ruby interpreter, and usually added to help understand unclear or complex pieces of code.
Single line comment
This is the most common type of comment.
Here is what the syntax looks like:
# I am a comment :)
A single line comment: * Begins with the # character * Any characters inside the comment, including code are completely ignored by the Ruby interpreter - useful for commenting out code.
A single line comment does not have to occur on it's own line, or at the beginning of the line, for example:
sum(1, 2) # Sums 1 & 2 and then prints.
You can easily do multi-line comments in Ruby using single lines comments
# This is a multi-line comment # I am made up of single line comments # Isn't this fun.
Another, rarely used way of writing multi-line comments is a special syntax that starts with
=begin and ends with
=end. For example:
=begin Between =begin and =end, You can write any number of lines. This will all be ignored by the Ruby interpreter. =end
What is a SheBang comment?
A SheBang comment (
#!), is a special kind of comment, that tells the Unix shell
how to properly interpret the file.
A SheBang comment appears at the top of a file, and allows you to run your Ruby file as an executable, assuming you have the correct permissions.
An example of a SheBang comment: