Comments are text in code that won't be executed by the interpreter, used to explain code functionality, record information, or temporarily disable code. Good commenting habits are an important part of writing high-quality code. This chapter will introduce in detail the various commenting methods in Ruby and their best practices.
In Ruby, use the # symbol to create single-line comments. All content from # to the end of the line will be ignored.
ruby
# This is a single-line commentputs "Hello, World!" # This is also a comment, following code# Calculate sum of two numbersdef add(a, b) a + b # Return sum of two numbersend# Variable declarationname = "Zhang San" # User nameage = 25 # User age
Ruby provides =begin and =end to create multi-line comment blocks:
ruby
=beginThis is a multi-line comment blockCan contain multiple lines of contentUsed to explain complex code logic in detail=endputs "Hello, World!"=beginComplex algorithm explanation:1. First initialize data structure2. Then perform data processing3. Finally output results=enddef complex_algorithm # Algorithm implementationend
# =begin and =end must start at the beginning of the line, no spaces before# Correct写法:=beginCorrect comment block=end# Incorrect写法 (won't be recognized as comment): =begin Incorrect comment block =end
class DataProcessor def initialize @data = [] end # TODO: Implement data validation feature def validate_data # To be implemented end # FIXME: Fix boundary condition handling def process_item(item) # Current implementation may have issues item.process end # HACK: Temporary solution, needs refactoring def quick_fix # Temporary fix code end # NOTE: This method has special behavior def special_behavior # Special handling logic end # OPTIMIZE: Performance can be optimized def slow_operation # Time-consuming operation endend
Ruby uses RDoc tool to generate documentation, supporting specific comment formats:
ruby
# Calculator class# Provides basic mathematical operationsclass Calculator # Create a new calculator instance def initialize @history = [] end # Addition operation # # Parameters: # a - First addend (Numeric) # b - Second addend (Numeric) # # Returns: # Sum of two numbers (Numeric) # # Example: # calc = Calculator.new # result = calc.add(2, 3) # => 5 def add(a, b) result = a + b @history << "#{a} + #{b} = #{result}" result end # Subtraction operation # # Parameters: # a - Minuend (Numeric) # b - Subtrahend (Numeric) # # Returns: # Difference of two numbers (Numeric) def subtract(a, b) result = a - b @history << "#{a} - #{b} = #{result}" result end # Get calculation history # # Returns: # Calculation history array (Array<String>) def history @history.dup endend
YARD is another popular Ruby documentation generation tool, supporting richer markup syntax:
ruby
# @author Zhang San# @since 1.0.0class User # @return [String] User name attr_accessor :name # @return [Integer] User age attr_accessor :age # Create new user # # @param name [String] User name # @param age [Integer] User age # @param email [String] User email def initialize(name, age, email = nil) @name = name @age = age @email = email end # Check if user is an adult # # @return [Boolean] Returns true if age is greater than or equal to 18 # # @example # user = User.new("Zhang San", 20) # user.adult? # => true def adult? @age >= 18 end # @!attribute [r] created_at # @return [Time] User creation time attr_reader :created_atend
# Good comments: Explain why, not what# Due to API limitation, need to validate email format before sendingif valid_email?(user.email) send_welcome_email(user)end# Avoid obvious comments# x = x + 1 # Increment x value (unnecessary comment)# Good comments: Explain complex logic# Use quicksort algorithm, average time complexity O(n log n)def quick_sort(array) return array if array.length <= 1 pivot = array.delete_at(rand(array.length)) left, right = array.partition { |x| x < pivot } quick_sort(left) + [pivot] + quick_sort(right)end
# Good comment format: Capitalize first letter, end with punctuation# Calculate user age.# Multi-line comments maintain consistent indentation# This is a longer comment,# used to explain complex business logic,# requiring multiple lines to fully describe.# Parameter descriptions use consistent format# Parameters:# name - User name# age - User age
class DataProcessor # Initialize data processor # Set default processing parameters def initialize @data_list = [] @processing_status = :pending end # Add data item # # Parameters: # item - Data item to add # # Returns: # Boolean - Whether addition succeeded def add_item(item) if item.nil? puts "Error: Item cannot be empty" return false end @data_list << item @processing_status = :has_data if @data_list.length == 1 true end # Process all data # Process each item in the data list according to predefined rules def process_data return if @data_list.empty? @data_list.each_with_index do |item, index| puts "Processing item #{index + 1}: #{item}" # Actual processing logic end @processing_status = :completed endend
def complex_method # TODO: Implement caching mechanism # FIXME: Fix memory leak issue # HACK: Temporarily bypass API limitation # NOTE: Implementation here may need optimization # OPTIMIZE: Consider using more efficient algorithm # WARNING: This method may have issues under high concurrency # DEPRECATED: This method will be removed in next version # Method implementationend
# Good comment scenarios:# 1. Complex algorithm explanation# Use Dijkstra algorithm to calculate shortest pathdef dijkstra(graph, start_node) # Algorithm implementationend# 2. Business logic explanation# Calculate discount rate based on user level# Regular user: 0%, Gold user: 5%, Diamond user: 10%def calculate_discount(user_level) case user_level when :regular then 0 when :gold then 0.05 when :diamond then 0.10 else 0 endend# 3. Non-obvious code# Due to floating point precision issues, use BigDecimal for accurate calculationrequire 'bigdecimal'def precise_calculation(a, b) BigDecimal(a.to_s) + BigDecimal(b.to_s)end
# Avoid comment scenarios:# 1. Obvious codex = 0 # Set x to 0 (unnecessary comment)# 2. Outdated comments# Calculate user points (actual code has changed to calculate user level)def calculate_user_level(user) # Implementationend# 3. Redundant comments# Loop through arrayarray.each do |item| # Process each item process_item(item)end
Ruby Comments
Comments are text in code that won't be executed by the interpreter, used to explain code functionality, record information, or temporarily disable code. Good commenting habits are an important part of writing high-quality code. This chapter will introduce in detail the various commenting methods in Ruby and their best practices.
💬 Single-Line Comments
Basic Syntax
In Ruby, use the
#symbol to create single-line comments. All content from#to the end of the line will be ignored.Comment Placement
📝 Multi-Line Comments
Using =begin and =end
Ruby provides
=beginand=endto create multi-line comment blocks:Notes
🎯 Comment Uses
1. Code Explanation
2. Temporarily Disable Code
3. TODO Comments
📚 Documentation Comments
RDoc Format
Ruby uses RDoc tool to generate documentation, supporting specific comment formats:
YARD Format
YARD is another popular Ruby documentation generation tool, supporting richer markup syntax:
🎨 Comment Style Guide
1. Comment Content
2. Comment Format
3. Chinese Comments
🛠️ Comment Tools and Techniques
1. Comment Templates
2. Conditional Comments
3. Comment Marks
🧪 Comment Practice Examples
Complete Comment Example
🎯 Comment Best Practices
1. When to Add Comments
2. When to Avoid Comments
3. Maintain Comments
📚 Next Steps
After mastering Ruby comments, it is recommended to continue learning:
Continue your Ruby learning journey!