Skip to content
AgileLogics
4 min read

Comments and Code Style

Prerequisites: Methods

A comment is a note for humans. Ruby ignores it completely.

# This is a full-line comment
tax_rate = 0.2 # a comment at the end of a line

Ruby has a block-comment syntax (=begin ... =end), but almost nobody uses it — just put # on each line.

What to comment

Good code explains what it does through clear names. Comments are for why — the reasoning a reader can't see from the code:

# Bad: repeats the code
count += 1 # add one to count

# Good: explains a non-obvious reason
# The API counts from 1, so shift our 0-based index.
page = index + 1

Ruby style in brief

The community style (collected in the Ruby Style Guide) is widely followed:

  • Two-space indentation, no tabs.
  • snake_case for variables and methods; CamelCase for classes and modules; SCREAMING_SNAKE_CASE for constants.
  • ? at the end of methods that return booleans.
  • Prefer { } for one-line blocks and do ... end for multi-line ones.
  • Prefer double quotes unless you need a literal #{.

You don't need to memorize these. RuboCop — a tool covered in Level 2 — checks your code against the style guide and fixes most issues automatically.

Magic comments

A few special comments at the top of a file change how Ruby reads it. The one you'll see most is:

# frozen_string_literal: true

It makes every string literal in the file unchangeable, which catches accidental changes and saves memory. The Frozen Objects lesson in Level 2 explains it.