Comments (Ruby)
Comments are used to describe the intent and specifications of code. Ruby has four types: single-line comments with #, multi-line comments with =begin...=end, RDoc-style documentation comments, and magic comments that instruct the interpreter on how to behave.
Syntax
# Single-line comment. Everything after # to the end of the line is a comment. # For multiple lines, put # at the start of each line. =begin Multi-line comment. =begin and =end must be written at the start of a line (column 0). Adding indentation causes a syntax error. =end # RDoc-style documentation comment. Written immediately before a method definition. # @param param_name [Type] Description # @return [Type] Description of the return value # @raise [ExceptionClass] When the exception is raised def method_name(arg) end # frozen_string_literal: true # Magic comment. Written on the first line of the file. # This freezes all string literals in the file (makes them immutable).
Comment Types and Uses
| Type | Syntax | Main Use |
|---|---|---|
| Single-line comment | # | Adds a short description above or at the end of code. Used most frequently. |
| Multi-line comment | =begin...=end | Comments out a large block at once. Consecutive # lines are common in modern Ruby. |
| RDoc comment | # with tags | Documents the public API of classes and methods. Read by the rdoc command and yard. |
| Magic comment | # key: value | Instructs the interpreter on file behavior — encoding, immutable strings, and so on. |
Main RDoc Tags
| Tag | Description |
|---|---|
@param name [Type] desc | Documents a method argument. Write one line per argument. |
@return [Type] desc | Documents the return value's type and content. |
@raise [ExceptionClass] desc | Documents exceptions that may be raised. |
@example | Shows a usage example. |
@deprecated | Marks the feature as deprecated. |
@see | References related classes or methods. |
Main Magic Comments
| Magic comment | Description |
|---|---|
# frozen_string_literal: true | Freezes all string literals in the file. Prevents unintended mutation and contributes to performance. Adopted as standard in many modern projects including Rails. |
# encoding: UTF-8 | Specifies the file encoding. Generally unnecessary since Ruby 2.0 defaults to UTF-8. |
# warn_indent: true | Outputs warnings for indentation inconsistencies. |
Sample Code
The basic writing style and placement of single-line comments.
comment_basic.rb
# Block comment: written above the code to describe the next operation.
# Hash mapping character names to combat styles
fighters = {
"Kiryu Kazuma" => "Dragon of Dojima", # Legendary combat style
"Majima Goro" => "Mad Dog of Shimano", # Versatile — switches styles freely
"Sawamura Haruka" => "none", # Non-combat character
"Akiyama Shun" => "Beast", # Powerful style using the environment
"Saejima Taiga" => "Tiger", # Martial arts from Okinawa
}
# Inline comment: a short note written to the right of code.
# By convention, leave two or more spaces before the #.
player_count = fighters.size # Gets the number of elements in the hash
puts "Registered characters: #{player_count}"
# Extract only combat-capable characters.
combatants = fighters.reject { |_name, style| style == "none" }
combatants.each do |name, style|
puts "#{name} (#{style})"
end
ruby comment_basic.rb Registered characters: 5 Kiryu Kazuma (Dragon of Dojima) Majima Goro (Mad Dog of Shimano) Akiyama Shun (Beast) Saejima Taiga (Tiger)
Comparing =begin...=end multi-line comments with the modern consecutive # style.
multiline_comment.rb
=begin
Example of a multi-line comment.
=begin and =end must be written at column 0 (no indentation).
Adding indentation causes a SyntaxError.
In modern Ruby style, consecutive # lines are common.
=end
# The same content rewritten with #:
# Example of a multi-line comment.
# # can be placed anywhere — not just at column 0 — so it can be indented with code.
# It also works well with editor "toggle comment" shortcuts.
# Define character stats.
characters = [
{ name: "Kiryu Kazuma", hp: 1200, style: "Dragon of Dojima" },
{ name: "Majima Goro", hp: 1000, style: "Mad Dog of Shimano" },
{ name: "Akiyama Shun", hp: 900, style: "Beast" },
]
# Output characters with HP of 1000 or more.
characters.each do |chara|
next unless chara[:hp] >= 1000 # Skip if HP is insufficient
puts "#{chara[:name]} (#{chara[:style]}) HP: #{chara[:hp]}"
end
ruby multiline_comment.rb Kiryu Kazuma (Dragon of Dojima) HP: 1200 Majima Goro (Mad Dog of Shimano) HP: 1000
Attaching RDoc-style documentation comments to a method. Using yard generates HTML documentation automatically.
rdoc_comment.rb
# Class representing a Like a Dragon character.
# Manages name, HP, and combat style, and calculates combat power.
class Fighter
attr_reader :name, :hp, :style
# Initializes a Fighter instance.
#
# @param name [String] The character's name.
# @param hp [Integer] Maximum HP. Must be greater than 0.
# @param style [String] The name of the combat style.
def initialize(name, hp, style)
@name = name
@hp = hp
@style = style
end
# Calculates and returns the combat power score.
# Multiplies HP by the style bonus.
#
# @param bonus [Integer] Style bonus multiplier. Default is 1.
# @return [Integer] The calculated combat power score.
# @raise [ArgumentError] Raised when bonus is 0 or less.
#
# @example
# f = Fighter.new("Kiryu Kazuma", 1200, "Dragon of Dojima")
# f.power_score(2) #=> 2400
def power_score(bonus = 1)
raise ArgumentError, "bonus must be 1 or greater." if bonus <= 0
@hp * bonus
end
# Returns character information as a formatted string.
#
# @return [String] String in "Name (Style) HP: XXX" format.
def info
"#{@name} (#{@style}) HP: #{@hp}"
end
end
kiryu = Fighter.new("Kiryu Kazuma", 1200, "Dragon of Dojima")
majima = Fighter.new("Majima Goro", 1000, "Mad Dog of Shimano")
saejima = Fighter.new("Saejima Taiga", 950, "Tiger")
puts kiryu.info
puts majima.info
puts saejima.info
puts "---"
[kiryu, majima, saejima].each do |f|
puts "#{f.name} power score: #{f.power_score(2)}"
end
ruby rdoc_comment.rb Kiryu Kazuma (Dragon of Dojima) HP: 1200 Majima Goro (Mad Dog of Shimano) HP: 1000 Saejima Taiga (Tiger) HP: 950 --- Kiryu Kazuma power score: 2400 Majima Goro power score: 2000 Saejima Taiga power score: 1900
Checking the effect of the magic comment # frozen_string_literal: true.
frozen_string.rb
# frozen_string_literal: true
# This magic comment must be on the first line of the file.
# All string literals in the file become frozen (immutable).
# Verify that the string is frozen.
name = "Kiryu Kazuma"
puts name.frozen? # true: the string is frozen
# Attempting to modify a frozen string raises an exception.
begin
name << " (Dragon of Dojima)" # << is a destructive method
rescue FrozenError => e
puts "Error: #{e.message}"
end
# Use dup to create a mutable copy.
mutable_name = name.dup # dup creates an unfrozen copy
mutable_name << " (Dragon of Dojima)"
puts mutable_name # The copy can be modified
# Non-destructive operations (+ and interpolation) work fine.
full_title = name + " - Dragon of Dojima"
puts full_title
puts "Character: #{name}"
# String.new explicitly creates an unfrozen string.
styles = String.new
styles << "Dragon of Dojima, "
styles << "Mad Dog of Shimano, "
styles << "Tiger"
puts styles
ruby frozen_string.rb true Error: can't modify frozen String: "Kiryu Kazuma" Kiryu Kazuma (Dragon of Dojima) Kiryu Kazuma - Dragon of Dojima Character: Kiryu Kazuma Dragon of Dojima, Mad Dog of Shimano, Tiger
Overview
Single-line comments using # are the standard in Ruby. Multi-line comments with =begin...=end exist, but since =begin and =end must be placed at the start of the line, consecutive # lines are common in modern code. This style is also compatible with editor toggle-comment shortcuts and can be indented to match the surrounding code, improving readability.
RDoc-style documentation comments are written with # immediately before method or class definitions. Tags such as @param, @return, and @raise structure the documentation. The rdoc command generates HTML documentation, and yard (Yet Another Ruby Documentation Tool) is used as standard in modern Ruby projects. yard is compatible with RDoc tags and offers more flexible customization and richer HTML output.
When the magic comment # frozen_string_literal: true is placed on the first line of a file, all string literals in that file become frozen. Attempting to modify a frozen string with a destructive method like << raises a FrozenError. When mutation is needed, use dup to copy the string or use String.new. The number of projects that add this comment to new files is increasing.
Common Mistakes
Adding indentation to =begin / =end causes a SyntaxError
=begin and =end must be written at the start of the line (column 0). Adding spaces or tabs for indentation causes a syntax error. When you want to align comments with the surrounding code, use consecutive # lines instead.
begin_end_ng.rb
def kiryu_info =begin Basic info for Kiryu Kazuma Affiliation: Dojima Family =end puts "Dragon of Dojima" end
ruby begin_end_ng.rb begin_end_ng.rb:2: syntax error, unexpected local variable or method
After fix:
begin_end_ok.rb
=begin Basic info for Kiryu Kazuma Affiliation: Dojima Family =end def kiryu_info # Using # instead of =begin...=end has no indentation restriction # Basic info for Kiryu Kazuma # Affiliation: Dojima Family puts "Dragon of Dojima" end kiryu_info
ruby begin_end_ok.rb Dragon of Dojima
Writing a magic comment on a line other than line 1 makes it ineffective
A magic comment such as # frozen_string_literal: true must be on the first line of the file to take effect. When a shebang line (#!/usr/bin/env ruby) is present, the second line is also allowed, but otherwise only line 1 is valid. If a comment or code appears before it, the magic comment has no effect.
magic_ng.rb
# Character definition for Majima Goro # frozen_string_literal: true # On line 2 or later — has no effect name = "Majima Goro" puts name.frozen? # false (not frozen)
ruby magic_ng.rb false
After fix:
magic_ok.rb
# frozen_string_literal: true # Magic comment must be on the first line # Character definition for Majima Goro name = "Majima Goro" puts name.frozen? # true (frozen)
ruby magic_ok.rb true
Placing the #! shebang line on a line other than line 1 prevents execution
The shebang line (#!/usr/bin/env ruby) must be on the first line of the file. The Unix kernel reads only the first line when executing a script to determine the interpreter. Writing it on any other line makes it just a comment, and even after chmod +x, the specified interpreter is not used.
shebang_ng.rb
# Saejima Taiga stats #!/usr/bin/env ruby # Shebang on line 2 is not recognized by the kernel puts "Tiger"
chmod +x shebang_ng.rb ./shebang_ng.rb ./shebang_ng.rb: line 1: Saejima: command not found
After fix:
shebang_ok.rb
#!/usr/bin/env ruby # Saejima Taiga stats puts "Tiger"
chmod +x shebang_ok.rb ./shebang_ok.rb Tiger
If you find any errors or copyright issues, please contact us.