Page Content

Tutorials

What Is Mean By Comments In Ruby With Code Examples

Comments in Ruby

Comments in Ruby are programmer-readable annotations that are ignored by the Ruby interpreter during runtime. Their primary purpose is to make source code easier for humans to understand, and they can also be used to temporarily disable parts of a program. Ruby has different methods for writing single-line and multi-line comments.

Single-Line Comments

In Ruby, the pound character (#) is used to start single-line comments. The Ruby interpreter ignores everything from that line’s end to the # character. Other names for the # character include mesh, hash, octothorpe, and pound sign.

To explain code segments or to temporarily “disable” a line of code, single-line comments can be written on their own line. Another way to use them is to append them to the end of a line of code, in which case everything that comes before the # is handled as regular Ruby code. A # is inserted before each line in this style to comment out several lines.

Code Example for Single-Line Comments:

# This is a comment that occupies an entire line.

puts "Hello World" # This is an inline comment, explaining the code on the same line.

# puts "This line is 'disabled' and will not run".

Output

Hello World

The # character is regarded as a regular character and does not start a comment when it appears inside a string literal or regular expression literal.

Code Example for # within a String:

puts "The # character inside a string is just a character, not a comment."

Output

The # character inside a string is just a character, not a co

Ruby also uses # in comments to denote the return value of an expression in documentation or interactive Ruby (IRB) examples, often with =>. For displaying expected output without a return value, a comment without => is used on a new line. Special comments like # -*- coding: utf-8 -*- are ignored as code by Ruby but are recognized for file format detection or by text editors.

Multi-Line Comments (Embedded Documents)

An embedded document is a type of multi-line comment that Ruby provides. It starts with =begin and goes on until (and includes) a line that starts with =end. To be functional, these identifiers must be the first characters on their lines (i.e., in column 1). If there is at least one space between =begin and =end, any text that follows on the same line is regarded as part of the comment and is ignored.
A handy method for commenting out lengthy code blocks without having to preface each line with # is to use embedded documents. Block comments, which use =begin and =end, cannot be placed in the midst of a line of code, though.

Code Example for Multi-Line Comments:

=begin
This is a multiline comment.
It can span across several lines of code.
The Ruby interpreter will ignore all content between =begin and =end.
puts "This code within the =begin/=end block will not execute."
=end

puts "This code will run because it is outside the comment block."

Output

This code will run because it is outside the comment block.

Note, “There are no multi-line comments” in Ruby for general code, =begin and =end are valid for multi-line comments. The use of =begin and =end as multi-line comment markers is, nevertheless, continuously supported by the thorough descriptions and examples.

Documentation Comments (RDoc)

Method, class, and module definitions can be preceded by specially structured comments that include embedded API description in Ruby scripts. The ri command-line application is used to explore the HTML documentation pages that are created using these comments by the rdoc tool.

RDoc comments can begin with =begin rdoc and be authored as embedded documents or as regular multi-line # comments. Like wikis, they allow a basic markup grammar that includes things like headings (like = Heading), lists (like * List Item), and literal code (like indented lines). Additionally, RDoc generates hyperlinks to other classes, methods (using #method_name), or source files that are mentioned in the comments automatically.

Control over documentation is made possible via RDoc Directives:

  • :nodoc: Conceals a component from the documentation that is produced.
  • :doc: Compels an attribute or method that would typically be hidden (such as a private method) to be documented.

Code Example for RDoc Comments:

# This is a documentation comment for the 'calculate_area' method.
#
# The method takes +length+ (Numeric) and +width+ (Numeric) as parameters.
#
# It returns the calculated area of a rectangle.
#
# Example:
#   calculate_area(5, 10) # => 50.
#   calculate_area(2.5, 4) # => 10.0
#
def calculate_area(length, width)
  length * width
end

The provided Ruby code block defines a method named calculate_area and includes documentation comments with examples of its usage [Query].

In Ruby, lines beginning with a pound character (#) are comments and are ignored by the Ruby interpreter during execution. Therefore, the example method calls such as calculate_area(5, 10) and calculate_area(2.5, 4) are within comments and would not be executed as part of the program [Query].

The def calculate_area(length, width) ... end block simply defines the method itself. Defining a method does not, by itself, produce any output to the console when a script is run. While defining a method in Ruby 2.x returns a symbol representing its name, this is an internal return value and not printed to standard output.

Furthermore, the calculate_area method calculates length * width and returns this value. It does not contain any explicit printing statements like puts or print. Even if the example lines were uncommented and executed, without puts or print, their return values would not be displayed to the console. The # => notation used in the comments indicates the return value of an expression, as seen in an interactive Ruby session (IRB), not printed output.

Therefore, if this exact code block were executed as a Ruby script, it would produce no output.

Regular Expression Comments

It is also possible to use the syntax (?# comment) to incorporate comments directly within a regular expression. Furthermore, regular expressions with the x modifier support expanded syntax, which ignores whitespace and unescaped # characters inside the regex pattern itself to create more readable, commented patterns.

Code Example for Regular Expression Comments:

# Using a comment within a regular expression.
pattern_inline = /R(?# this comment is part of the regex)uby/
puts "Ruby".match(pattern_inline) # => #<MatchData "Ruby">

# Using the 'x' modifier for extended regex comments and whitespace.
pattern_extended = /
  ^R          # Matches 'R' at the start of the string
  (uby)+      # Matches one or more 'uby' sequences
  $           # Matches the end of the string
/x
puts "Rubyuby".match(pattern_extended) # => #<MatchData "Rubyuby">

Output

Ruby
Rubyuby

You can also read Introduction To Ruby, Why It Is Used, Versions And Set Up

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index