Introduction To Ruby
Writing Comments

Introduction

Programmers write comments in their code to make that code easier to understand. Interpreters and compilers ignore the comments - adding comments does not make the program 'longer' or 'less efficient'. Comments make it easier for you to remember what parts of your code mean as well as making it easier for others to understand and adapt the code you have written.

Ruby Comments

If we take the Hello World program from the previous page, we might add the following comments,

# Hello World Program

# Outputs 'Hello World' to the console and adds a line break
puts "Hello World"
# Stops the program from finishing until the enter key is pressed
gets

Notice that we use the hash symbol (#) to write a comment.

Alternatively, we might comment the code as follows,

# Hello World Program

puts "Hello World" # Output 'Hello World' and a line break
gets # Wait for user to press enter

Embedded Documents

There are times when we want to write a little more detail in our comments and our comments need to span more than one line to be readable. In these cases, we can create an embedded document and avoid having to write a # at the start of each line,

=begin
This is my Hello World Program.

It only has two lines of code but I'm really proud of it.

It outputs the phrase, 'Hello World' to the console and then waits for the enter key to be pressed.
=end


puts "Hello World"
gets

Challenges

Again, we haven't covered enough material yet for a real challenge. All of the examples on this page have exactly the same two lines of code. The inclusion of the comments makes no actual difference to the way that the program is interpreted. You can make and run all of these samples to prove that to yourself.