liveBook · Manning

Ruby parser

As explained in The Well-Grounded Rubyist, Fourth Edition

The Ruby parser is the component that analyzes Ruby source code and determines its syntactic structure and variable classifications.

The Ruby parser analyzes source before execution and classifies local variables. When it sees identifier = value, it allocates the local variable even if the surrounding code never runs. section 6.1.2

A local variable created by unreachable code

In `if false; x = 1; end`, the assignment never executes, but `x` exists and evaluates to nil. An unmentioned variable such as `y` instead raises a fatal error. This parse-time distinction matters because local variables resemble method calls, while instance and global variables have recognizable prefixes. section 6.1.2

if false
  x = 1
end
p x      #1
p y      #2

Compare a parser-created local variable with a nonexistent variable in a failing conditional. section 6.1.2

The same parse-time awareness makes assignment in a conditional test easy to misuse: `if x = 1` assigns and tests the value, and Ruby may warn that `==` was intended. Parenthesized expressions or a separate assignment make the intent clearer. section 6.1.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Descends to parse-time allocation and nil behavior, then stops short of broader parser implementation details.
Examples
Uses failing conditionals, assignment tests, parser warnings, and regular-expression matching assignments.
What you can do after
Diagnose surprising nil values, nonexistent-variable errors, and accidental assignment in conditional tests.
How it connects
Links local variables with assignment, conditional expressions, method calls, instance variables, and global variables.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.