|
|
Line 1: |
Line 1: |
| == Closures == | | == Closures == |
| ===What is a Closure?=== | | ===What is a Closure?=== |
| A closure is a block of code that can access the lexical environment of its definition. A closure has two properties:
| | ===Closures in Ruby=== |
| | |
| - A closure can be passed as an object.
| |
| - A closure recalls the values of all the variables that were in scope when the function was created and is able to access those variables when it is called even though they may no longer be in scope.
| |
| | |
| A closure can be thought of as essentially a function pointer that references a block of executable code and the variables from the scope it was created.
| |
| | |
| ===Closures in Ruby=== | |
| Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are Blocks.
| |
| ====Blocks==== | | ====Blocks==== |
| ====Procs and Lambdas==== | | ====Procs and Lambdas==== |
| When creating a lambda or proc, the object holds a reference to the executable block and bindings for all the variables used by the block. In Ruby, we can create a Proc object explicitly in three different ways.
| |
| 1. Using Proc.new
| |
| 2. Using the proc method in the Kernel module
| |
| 3. Using the lambda method in the Kernel module
| |
|
| |
| ===Why use Closures?=== | | ===Why use Closures?=== |
| Closures allow programmers to provide functionality with less code, since it stores state information.
| |
|
| |
|
| ==Currying == | | ==Currying == |