Skip to the workspace
Pebellslearn by building
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.

ruby / Comments

Explore each scene at your own pace.

01 · The rule

The rule

Comments

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

Explain a non-obvious decision without repeating what the source already says.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.