Ruby Procs

Blocks are not objects, but they can be converted into objects of class Proc. This can be done by calling the lambda method of the class Object. A block created with lambda acts like a Ruby method. If you don't specify the right number of arguments, you can't call the block.

Proc objects are blocks of code that have been bound to a set of local variables. The class Proc has a method call that invokes the block. The program p024proccall.rb illustrates this.

The output is:

Remember you cannot pass methods into other methods (but you can pass procs into methods), and methods cannot return other methods (but they can return procs).

The next example shows how methods can take procs. Example p025mtdproc.rb

The output is:

Here's another example of passing arguments using lambda.

Fabio Akita a Brazilian Rails enthusiast, also known online as "AkitaOnRails", wrote this exclusive article on Ruby Blocks/Closures for the members like you. Do read, after you have gone through this lesson.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on and in the course at is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.