Ruby

Use Comments in Ruby

ruby-logo

Use Comments in Ruby

Introduction

The comments are lines in computer programs that are avoid by compilers and interpreters. You will use comments to create your programs easier for different programmers to know by using them to produce additional context or clarification regarding what each part of a program is doing.

You will use comments to clarify why you selected a particular solution, or even prevent a problematic or incomplete a part of your program from executing temporarily while you work out a fix.

The some comments may stay within the code forever, like those that explain context, whereas different comments are often temporary, like notes you permit yourself whereas you are building your program.

Let’s check out the way to use comments in Ruby programs to leave notes, as well as the way to use them as a debugging tool.

Comment Syntax and Usage

Comments in Ruby begin with a hash mark (#) and continue to the end of the line, like this:

# This is a comment in Ruby

While it is not needed, you ought to place a blank space after the hash mark to enhance the comment’s readability.

When you run a program, you will not see any indication of comments within the code; the Ruby interpreter ignores them entirely. Comments are within the source code for humans to read, not for computers to execute.

greetings.rb
# 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 comments provide you with a general idea of what every section of the program will and the way it works.

In a program that iterates over an array and displays its contents as an HTML list, you would possibly see comments like this, that provides a very little additional clarification regarding what the code does:

sharks.rb
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 may not be familiar with things like map and join yet, however the comments provide you an idea of how this program should work and what the output may seem like. Try it out, Place this code in a file called sharks.rb and run it:

ruby sharks.rb

You’ll see the program’s output:

Output

<ul>
  <li>hammerhead</li>
  <li>great white</li>
  <li>dogfish</li>
  <li>frilled</li>
  <li>bullhead</li>
  <li>requiem</li>
</ul>

Notice you do not see the comments, since the interpreter ignored them. However the output probably matched what you were expecting. Comments are a excellent communication tool, particularly once the person reading the comments is new the language.

READ  Convert Data Types in Ruby

Comments ought to be created at constant indent as the code they commenting. That is, a class definition with no indentation would have a comment with no indentation, and each indentation level following would have comments that are aligned with the code it’s commenting.

For example, here could be a Ruby implementation of a Magic 8-Ball game. The computer can provides a random answer to an question you raise.

Notice that the comments are indented at constant level of indentation because the code in every section.

magic8ball.rb
# 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 supposed to help programmers, whether it is the original programmer or someone else using or collaborating on the project. This means the comments must be maintained just like the code. A comment that contradicts the code is worse than no comment at all.

When you’re just starting out, you may write lots of comments to help you understand what you’re doing. But as you gain more experience, you should be looking to use comments to explain the why behind the code as opposed to the what or how. Unless the code is particularly tricky, looking at the code can generally tell what the code is doing or how it is doing it.

For example, this kind of comment isn’t that helpful once you know Ruby:

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

This comment reiterates what the code already does, and while it doesn’t affect the program’s output, it is extra noise when you’re reading code.

Sometimes you’ll need to write comments that are a little more detailed. That’s what block comments are for.

Block Comments

You will use block comments to clarify additional difficult code or code that you just don’t expect the reader to be familiar with. These longer-form comments apply to some or all of the code that follows, and are indented at same level as the code.

READ  Work with Arrays in Ruby

In block comments, each line begins with the hash mark followed by single space for readability. If you need to use over one paragraph, they must be separated by a line that contains one hash mark.

Here is an example of a block comment from the Sinatra web framework’s source code. It provides some context to other developers regarding how this particular code works:

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 great when you need to thoroughly explain pieces of code. However, you should try to avoid over-commenting your code, as those comments could be redundant and create additional noise. Trust other programmers to understand Ruby code unless you are writing for a particular audience. Comments should add context, not duplicate the code.

Ruby has an alternative syntax for multi-line comments, but it’s rarely used. Here’s an example:

multiline.rb
=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 must be at the start of the line. They cannot be indented. It’s for this reason that you will rarely see this used.

Let’s check out inline comments next.

Inline Comments

Inline comments occur on same line of a statement, following the code itself. Like other comments, they start with a hash mark, followed by one white-space character for readability.

Generally, inline comments seem like this:

[code]  # Inline comment about the code

Inline comments should be used meagerly, however are often effective for explaining difficult or non-obvious of code. They will even be helpful if you think that you will not remember a line of the code you’re writing within the future, or if you’re collaborating with somebody who you know may not be familiar with all aspects of the code.

READ  To Work with String Methods in Ruby

For example, if you don’t use a lot of math in your Ruby programs, you or your collaborators may not understand that the subsequent creates a complex number, thus you will wish to include an inline comment regarding that:

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

You can also use inline comments to explain the reason behind doing something:

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

Comments that are made in line should be used only when necessary and when they can provide helpful guidance for the person reading the program.

Commenting Out Code for Testing

In addition to using comments as the simplest way to document code, you’ll use the hash mark to comment out code that you just don’t wish to execute whereas you’re testing or debugging a program you’re presently making. Sometimes, when you experience errors once adding new lines of code, you will wish to comment some of them out to see if you’ll troubleshoot the problem through the method of elimination.

For example, within the Magic 8-Ball game, maybe you wish to stop the sport from running once more as a result of you are simply fascinated by ensuring that the code evaluates the solution properly. You can simply comment out the line of code that starts the sport again.

8ball.rb
...

  # 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
...

Comments also let you try alternatives while you’re determining how to implement a solution in your code. For example, you may want to try a couple of different approaches when working with arrays in Ruby. You can use comments to test each approach and determine which one you like the most:

sharks.rb
sharks = ["Tiger", "Great White", "Hammerhead"]

# for shark in sharks do
#  puts shark
# end

sharks.each do |shark|
  puts shark
end

Commenting out code helps you to attempt completely different programming strategies as well as help you find the source of an error through systematically commenting out and running parts of a program.

Conclusion

Using comments within your Ruby programs will create programs additional clear to humans, including your future self. Including acceptable comments that are relevant and helpful makes it easier for others to collaborate with you on programming projects. They’ll also help you understand code you wrote within the future after you come back your project after a long period of time.

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment