Skip to content

Ruby Comments

Comments are annotations within your Ruby code that are ignored by the Ruby interpreter during execution. They are crucial for explaining complex parts of code, leaving notes for yourself or other developers, or temporarily disabling lines of code.

A single-line comment starts with a hash character (#) and extends to the end of that line. Anything after the # on that line is considered a comment.

#!/usr/bin/env ruby
# This is a single-line comment.
puts "Hello, Ruby!" # This is a trailing comment, explaining the 'puts' line.
# Another comment on its own line.
# x = 10 # This line of code is temporarily disabled (commented out).

When executed, the above program produces:

Hello, Ruby!

Ruby provides a way to write multiline comments using =begin and =end. These markers must be at the very beginning of their respective lines, with no preceding whitespace.

#!/usr/bin/env ruby
puts "Hello, Ruby!" # This line will be executed.
=begin
This is a multiline comment.
It can span as many lines as you like.
All lines between =begin and =end are ignored.
This is often used for longer explanations or for commenting out large blocks of code.
=end
puts "This line is after the multiline comment." # This will also be executed.

When executed, the program produces:

Hello, Ruby!
This line is after the multiline comment.
  • Clarity over Quantity: Write comments to explain why something is done, or to clarify complex logic, not just what the code does (which should be evident from well-written code itself).
  • Keep Comments Updated: If you change the code, make sure to update any relevant comments. Outdated comments can be more misleading than no comments.
  • Trailing Comments: Use trailing comments (at the end of a line of code) sparingly for brief notes. Ensure they are well-aligned if used in a block for readability.
  • Commenting Out Code: Use comments to temporarily disable blocks of code during debugging. Remember to remove or reinstate this code later.
  • Documentation Comments (RDoc/YARD): For more formal documentation (e.g., for libraries or APIs), Ruby uses conventions where specially formatted comments (often starting with ##) can be processed by tools like RDoc or YARD to generate documentation. This is beyond basic commenting but important for larger projects.

Example of aligning trailing comments:

class Config
@max_users = 100 # Maximum number of concurrent users
@timeout = 30 # Session timeout in seconds
@retries = 3 # Number of retries for a failed operation
end

Effective commenting makes your code more understandable and maintainable for yourself and others.