Using Comments in Ruby

Developers Working From Home Office.
vgajic/Getty Images

Comments in your Ruby code are notes and annotations meant to be read by other programmers. The comments themselves are ignored by the Ruby interpreter, so the text inside the comments isn't subject to any restrictions.

It's usually good form to put comments before classes and methods as well any piece of code that may be complex or unclear.

Using Comments Effectively

Comments should be used to give background information or annotate difficult code.

Notes that simply say what the next line of straightforward code does are not only obvious but also add clutter to the file.

It's important to take care not to use too many comments and to be sure the comments made in the file are meaningful and helpful to other programmers.

The Shebang

You'll notice that all Ruby programs start with a comment that begins with #!. This is called a shebang and is used on Linux, Unix and OS X systems.

When you execute a Ruby script, the shell (such as bash on Linux or OS X) will look for a shebang at the first line of the file. The shell will then use the shebang to find the Ruby interpreter and run the script.

The preferred Ruby shebang is #!/usr/bin/env ruby, though you may also see #!/usr/bin/ruby or #!/usr/local/bin/ruby.

Single-line Comments

The Ruby single-line comment begins with the # character and ends at the end of the line. Any characters from the # character to the end of the line are completely ignored by the Ruby interpreter.

The # character doesn't necessarily have to occur at the beginning of the line; it can occur anywhere.

The following example illustrates a few uses of comments.

 #!/usr/bin/env ruby
 # This line is ignored by the Ruby interpreter
 # This method prints the sum of its arguments
 def sum(a,b)
   puts a+b
 sum(10,20) # Print the sum of 10 and 20 

Multi-line Comments

Though often forgotten by many Ruby programmers, Ruby does have multi-line comments. A multi-line comment begins with the =begin token and ends with the =end token.

These tokens should start at the beginning of the line and be the only thing on the line. Anything between these two tokens is ignored by the Ruby interpreter.

 #!/usr/bin/env ruby
 Between =begin and =end, any number
 of lines may be written. All of these
 lines are ignored by the Ruby interpreter.
 puts "Hello world!"

In this example, the code would execute as Hello world!