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 code and the while statement for repeatedly executing code:

if x < 10 then   # If this expression is true
  x = x + 1      # Then execute this statement
end              # Marks the end of the conditional

while x < 10 do  # While this expression is true...
  print x        # Execute this statement
  x = x + 1      # Then execute this statement
end              # Marks the end of the loop

In Ruby, these statements are technically expressions, but there is still a useful distinction between expressions that affect the control flow of a program and those that do not. Chapter 5 explains Ruby’s control structures.

In all but the most trivial programs, we usually need to group expressions and statements into parameterized units so that they can be executed repeatedly and operate on varying inputs. You may know these parameterized units as functions, procedures, or subroutines. Since Ruby is an object-oriented language, they are called methods. Methods, along with related structures called procs and lambdas, are the topic of Chapter 6.

Finally, groups of methods that are designed to interoperate can be combined into classes, and groups of related classes and methods that are independent of those classes can be organized into modules. Classes and modules are the topic of Chapter 7.

Block Structure in Ruby

Ruby programs have a block structure. Module, class, and method definitions, and most of Ruby’s statements, include blocks of nested code. These blocks are delimited by keywords or punctuation and, by convention, are indented two spaces relative to the delimiters. There are two kinds of blocks in Ruby programs. One kind is formally called a “block.” These blocks are the chunks of code associated with or passed to iterator methods:

3.times { print "Ruby! " }

In this code, the curly braces and the code inside them are the block associated with the iterator method invocation 3.times. Formal blocks of this kind may be delimited with curly braces, or they may be delimited with the keywords do and end:

1.upto(10) do |x|
  print x
end

do and end delimiters are usually used when the block is written on more than one line. Note the two-space indentation of the code within the block. Blocks are covered in Blocks.

To avoid ambiguity with these true blocks, we can call the other kind of block a body (in practice, however, the term “block” is often used for both). A body is just the list of statements that comprise the body of a class definition, a method definition, a while loop, or whatever. Bodies are never delimited with curly braces in Ruby—keywords usually serve as the delimiters instead. The specific syntax for statement bodies, method bodies, and class and module bodies are documented in Chapters 5, 6, and 7.

Bodies and blocks can be nested within each other, and Ruby programs typically have several levels of nested code, made readable by their relative indentation. Here is a schematic example:

module Stats                          # A module
  class Dataset                       # A class in the module
    def initialize(filename)          # A method in the class
      IO.foreach(filename) do |line|  # A block in the method
        if line[0,1] == "#"           # An if statement in the block
          next                        # A simple statement in the if
        end                           # End the if body
      end                             # End the block
    end                               # End the method body
  end                                 # End the class body
end                                   # End the module body
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.153