Syntactic Structure
So far, we’ve discussed the tokens of a Ruby program and the characters that make them up. Now we move on to briefly describe how those lexical tokens combine into the larger syntactic structures of a Ruby program. This section describes the syntax of Ruby programs, from the simplest expressions to the largest modules. This section is, in effect, a roadmap to the chapters that follow.
The basic unit of syntax in Ruby is the
expression. The Ruby interpreter evaluates expressions,
producing values. The simplest expressions are primary
expressions, which represent values directly. Number and
string literals, described earlier in this chapter, are primary
expressions. Other primary expressions include certain keywords such as
true, false, nil,
and self. Variable references are
also primary expressions; they evaluate to the value of the
variable.
More complex values can be written as compound expressions:
[1,2,3] # An Array literal
{1=>"one", 2=>"two"} # A Hash literal
1..3 # A Range literal
Operators are used to perform computations on values, and compound expressions are built by combining simpler subexpressions with operators:
1 # A primary expression x # Another primary expression x = 1 # An assignment expression x = x + 1 # An expression with two operators
Chapter 4 covers operators and expressions, including variables and assignment expressions.
Expressions can be combined with Ruby’s keywords to create
statements, such as the if statement for conditionally executing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access