The Foundations of a Closure

Let’s begin with a definition of a closure. A closure is essentially a function whose body references a variable that is declared in the parent scope.

The key to understanding closures is to grasp two other programming language concepts: lexical scoping and free variables. Let’s look at lexical scoping first, and then dive into free variables.

Lexical Scoping: Closest Variable Wins

Lexical scoping rules serve to answer one question: what is the value of this variable at this line? In short, lexical scoping says that whichever assignment to a variable that is the closest gets that value.

The value of a variable x is given by the innermost statement that declares x. Furthermore, the area in a program where a variable ...

Get Mastering Ruby Closures 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.