CSC/ECE 517 Fall 2011/ch3 4b js: Difference between revisions
No edit summary |
|||
Line 9: | Line 9: | ||
===Closures in Ruby=== | ===Closures in Ruby=== | ||
Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are Blocks. | Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are 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. | 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. | ||
Line 15: | Line 16: | ||
2. Using the proc method in the Kernel module | 2. Using the proc method in the Kernel module | ||
3. Using the lambda 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. | Closures allow programmers to provide functionality with less code, since it stores state information. |
Revision as of 03:16, 15 October 2011
Closures
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:
- 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
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?
Closures allow programmers to provide functionality with less code, since it stores state information.