0
0
Rubyprogramming~5 mins

Comments and documentation in Ruby

Choose your learning style9 modes available
Introduction

Comments help explain what your code does in simple words. Documentation tells others how to use your code easily.

When you want to explain why a piece of code exists.
When you want to remind yourself what a tricky part of code does.
When you want to help others understand how to use your code.
When you want to temporarily stop a line of code from running.
When you write a method and want to describe its purpose and inputs.
Syntax
Ruby
# This is a single-line comment
=begin
This is a
multi-line comment
=end

# Documentation example:
# Adds two numbers and returns the result
# @param a [Integer] the first number
# @param b [Integer] the second number
# @return [Integer] the sum of a and b
def add(a, b)
  a + b
end

Single-line comments start with # and go to the end of the line.

Multi-line comments use =begin and =end on their own lines.

Examples
A simple single-line comment before a print statement.
Ruby
# This is a comment explaining the next line
puts "Hello, world!"
Multi-line comment that does not run, then a print statement.
Ruby
=begin
This is a multi-line comment.
It can span several lines.
=end
puts "Done"
Documentation comments before a method to explain its purpose and parameters.
Ruby
# Calculates the square of a number
# @param x [Integer] number to square
# @return [Integer] squared result
def square(x)
  x * x
end
Sample Program

This program uses comments to explain each part: the method, the inputs, and the output.

Ruby
# This program adds two numbers and shows the result

# Define a method to add two numbers
# a and b are the inputs
# Returns their sum

def add(a, b)
  a + b
end

# Call the method and store the result
result = add(5, 7)

# Show the result
puts "The sum of 5 and 7 is #{result}"
OutputSuccess
Important Notes

Comments do not affect how the program runs.

Use comments to make your code easier to understand for yourself and others.

Keep comments clear and short.

Summary

Comments explain code and start with # for single lines.

Multi-line comments use =begin and =end.

Documentation comments describe methods and their inputs/outputs.