Understanding Ruby blocks, Procs and methods  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
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.


Additionally, having some background in Lisp and years of Perl experience, I was unsure of how the Ruby concepts map to similar idioms from other programming languages, like Lisp’s functions and Perl’s subroutines. Sifting through hundreds of newsgroup posts, I saw that I’m not the only one with this problem, and in fact quite a lot of “Ruby Nubies” struggle with the same ideas.

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)
    return Proc.new {|n| n*factor }
end

times3 = gen_times(3)
times5 = gen_times(5)

times3.call(12)               #=> 36
times5.call(5)                #=> 25
times3.call(times5.call(4))   #=> 60

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.

Read more





User reviews

There are no user reviews for this item.

Add new review




Powered by jReviews

Last Updated ( Monday, 28 January 2008 )
 
< Prev   Next >