Introduction
Comments help explain what your code does in simple words. Documentation tells others how to use your code easily.
Comments help explain what your code does in simple words. Documentation tells others how to use your code easily.
# 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.
# This is a comment explaining the next line puts "Hello, world!"
=begin This is a multi-line comment. It can span several lines. =end puts "Done"
# Calculates the square of a number # @param x [Integer] number to square # @return [Integer] squared result def square(x) x * x end
This program uses comments to explain each part: the method, the inputs, and the output.
# 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}"
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.
Comments explain code and start with # for single lines.
Multi-line comments use =begin and =end.
Documentation comments describe methods and their inputs/outputs.
# to start a single-line comment.=begin and =end to mark multi-line comments.def greet(name)
# This method returns a greeting message
"Hello, #{name}!"
end
puts greet("Alice")=begin This is a multi-line comment # Another comment line =end puts "Done"
=begin and =end must be at the start of the line with no leading spaces.=begin or =end are indented or not at line start, Ruby raises a syntax error.@param and @return to document methods clearly.Pass the test and this pattern moves unknown