Ruby - Procs and Lambdas

Introduction

Blocks 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

The three cases above create an instance of the Proc class.

It is the Ruby "object wrapper" for a block.

The following code shows how to create and use a Proc object.

Demo

a = Proc.new{|x| x = x*10; puts(x)}
a.call(100)        #=> 1000
# from www  .jav  a  2s.c o  m
b = lambda{|x| x = x*10; puts(x) }
b.call(100)            #=> 1000

c = proc{|x| x.capitalize! }
c1 = c.call( "hello" )
puts( c1 )             #=> Hello

Result

Related Topics