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 printedFor 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.
=endA 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: trueIt 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.
The original
cups_sold += 1 # add 1 to cups_soldrepeats 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.
What does Ruby do with total *= 1.05 # add tax?
What does puts "Order #42 ready" print?
What does the magic comment # frozen_string_literal: true do?
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/=endthat are not at the start of a line.
