O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required