Creating Objects from Blocks

Although blocks may not be objects by default, they can be “turned into” objects. There are three ways of creating objects from blocks and assigning them to variables—here’s how:

proc_create.rb

a = Proc.new{|x| x = x*10; puts(x) }    #=> Proc
b = lambda{|x| x = x*10; puts(x) }      #=> Proc
c = proc{|x| x.capitalize! }            #=> Proc

In each of the three cases, you will end up creating an instance of the Proc class—which is the Ruby “object wrapper” for a block.

Let’s take a look at a simple example of creating and using a Proc object. First, you can create an object calling Proc.new and passing to it a block as an argument:

3blocks.rb

a = Proc.new{|x| x = x*10; puts(x)}

Second, you can execute the code in the block to which a refers using ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.