Lexical Structure

The Ruby interpreter parses a program as a sequence of tokens. Tokens include comments, literals, punctuation, identifiers, and keywords. This section introduces these types of tokens and also includes important information about the characters that comprise the tokens and the whitespace that separates the tokens.

Comments

Comments in Ruby begin with a # character and continue to the end of the line. The Ruby interpreter ignores the # character and any text that follows it (but does not ignore the newline character, which is meaningful whitespace and may serve as a statement terminator). If a # character appears within a string or regular expression literal (see Chapter 3), then it is simply part of the string or regular expression and does not introduce a comment:

# This entire line is a comment
x = "#This is a string"               # And this is a comment
y = /#This is a regular expression/   # Here's another comment

Multiline comments are usually written simply by beginning each line with a separate # character:

#
# This class represents a Complex number
# Despite its name, it is not complex at all.
#

Note that Ruby has no equivalent of the C-style /*...*/ comment. There is no way to embed a comment in the middle of a line of code.

Embedded documents

Ruby supports another style of multiline comment known as an embedded document. These start on a line that begins =begin and continue until (and include) a line that begins =end. Any text that appears after =begin or =end is part of ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.