July 2011
Intermediate to advanced
400 pages
8h 46m
English
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! } #=> ProcIn 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 ...
Read now
Unlock full access