Understanding Ruby blocks, Procs and methods
|
|
|
|
| Articles Reviews Ruby | |
| Written by Adi Bach | |
| Monday, 12 February 2007 | |
|
Ruby provides the programmer with a set of very powerful features borrowed from the domain of functional programming, namely closures, high-order functions and first-class functions . These features are implemented in Ruby by means of code blocks, Proc objects and methods (that are also objects) - concepts that are closely related and yet differ in subtle ways.
In fact I found myself quite confused about this topic, having a difficulty to understand the difference between blocks, procs and methods and unsure about the best practices of using them. In this article I lay out my understanding of this facet of Ruby, which comes as a result of extensive research of Ruby books, documentation and comp.lang.ruby, in sincere hope that other people will find it useful as well. Procs Shamelessly ripping from the Ruby documentation, Procs are defined as follows: Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables. A useful example is also provided: def gen_times(factor) Procs play the role of functions in Ruby. It is more accurate to call them function objects, since like everything in Ruby they are objects. Such objects have a name in the folklore - functors. A functor is defined as an object to be invoked or called as if it were an ordinary function, usually with the same syntax, which is exactly what a Proc is. From the example and the definition above, it is obvious that Ruby Procs can also act as closures. On Wikipedia, a closure is defined as a function that refers to free variables in its lexical context. Note how closely it maps to the Ruby definition blocks of code that have been bound to a set of local variables. Powered by jReviews |
|
| Last Updated ( Monday, 28 January 2008 ) | |
| < Prev | Next > |
|---|







