Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Ruby Basics  ›  Lesson

Comments

Comments 12 minA # starts a comment that runs to the end of the line, and good comments explain why the code does something rather than repeating what it does.

Comments

Six months from now you will open the Bean Cart script and find the line total *= 1.05. Why 1.05? Was it tax, a tip, a mistake? A single comment would have saved you ten minutes of detective work. Comments are notes to humans; Ruby skips them.

The rule

A # hides the rest of the line; explain why, not what.

Everything from a # to the end of the line is ignored by Ruby, unless the # is inside a string:

# Add 5% sales tax, required by the city since 2024.
total *= 1.05

cups_sold += 1  # one more cup for the day
puts "Order #42 ready"   # this # is inside a string, so it is printed

For a long note, just use several # lines in a row. That is what almost all Ruby code does.

Ruby also has a block comment, =begin and =end, but both markers must start at the very beginning of a line, and it is rarely used in modern code:

=begin
Everything between these markers
is ignored by Ruby.
=end

A few special comments at the top of a file are read by Ruby itself. The one you will see most is this magic comment:

# frozen_string_literal: true

It makes the plain string literals written in that file (quoted text without #{} interpolation) unchangeable, which prevents accidental edits and saves memory. Many style guides add it to every file.

Finally, comments directly above a method or class are used as documentation by tools such as RDoc and YARD, which turn them into web pages.

The shortcut

Before writing a comment, read the code aloud. If the comment would just repeat what you said, delete it. If it answers a "why?" the code cannot, keep it.

Improving one Bean Cart commentStep 1 of 4
  1. The original

    cups_sold += 1 # add 1 to cups_sold repeats the code word for word.

A second trap: a comment that no longer matches the code is worse than none. When you change the code, update or delete its comment.

Drills

Answer fast — trust the rule.

quick drill

What does Ruby do with total *= 1.05 # add tax?

quick drill

What does puts "Order #42 ready" print?

quick drill

What does the magic comment # frozen_string_literal: true do?

quick drill

Which comment is most useful?

Remember

  • A # hides the rest of the line; explain why, not what.
  • Read the code aloud: if the comment repeats it, cut it.
  • Trap: stale comments that disagree with the code, and =begin/=end that are not at the start of a line.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainRewrite a weak comment

Bean Cart's code has total *= 1.05 # multiply total by 1.05. Explain what is wrong with this comment, rewrite it, and describe how Ruby treats the text after #.