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:
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 the Proc class’s call
method with one or more arguments (matching the block parameters) to be passed into the block; in the previous code, you could pass an integer such as 100, and this would be assigned to the block variable x
:
a.call(100) #=> 1000
Finally, you can also create a Proc object by calling the lambda
or proc
methods, which are supplied by the Kernel class. The name lambda
is taken from the Scheme (Lisp) language and is a term used to describe an anonymous method, or closure.
b = lambda{|x| x = x*10; puts(x) } b.call(100) #=> 1000 c = proc{|x| x.capitalize! } c1 = c.call( "hello" ) puts( c1 ) #=> Hello
Here is a slightly more complicated example that iterates over an array of strings, capitalizing each string in turn. The array of capitalized strings is then assigned to the d1
variable:
d = lambda{|x| x.capitalize! } d1 = ["hello","good day","how do you do"].each{ |s| d.call(s)} puts(d1.inspect) #=> ["Hello", "Good day", "How do you do"]
There is one important difference between creating a Proc object using Proc.new
and creating a Proc object using a lambda
method—Proc.new
does not check that the number of arguments passed to the block matches the number of block parameters. lambda
does. The behavior of the proc
method is different in Ruby 1.8 and 1.9. In Ruby 1.8, proc
is equivalent to lambda
—it checks the number of arguments. In Ruby 1.9, proc
is equivalent to Proc.new
—it does not check the number of arguments:
proc_lamba.rb
a = Proc.new{|x,y,z| x = y*z; puts(x) } a.call(2,5,10,100) # This is not an error b = lambda{|x,y,z| x = y*z; puts(x) } b.call(2,5,10,100) # This is an error puts('---Block #2---' ) c = proc{|x,y,z| x = y*z; puts(x) } c.call(2,5,10,100) # This is an error in Ruby 1.8 # Not an error in Ruby 1.9
18.225.72.245