Ruby 2 Procs

Blocks are not objects, but they can be converted into objects of class Proc. This can be done by calling the lambdamethod 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.
  1. prc = lambda {"hello"}  
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.
  1. # Blocks are not objects  
  2. # they can be converted into objects of class Proc by calling lambda method  
  3. prc = lambda {puts 'Hello'}  
  4. # method call invokes the block  
  5. prc.call  
  6.   
  7. # another example  
  8. toast = lambda do  
  9.   'Cheers'  
  10. end  
  11. puts toast.call  
The output is:
  1. >ruby p024proccall.rb  
  2. Hello  
  3. Cheers  
  4. >Exit code: 0  
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
  1. =begin  
  2.   You cannot pass methods into other methods (but you can pass procs into methods),  
  3.   and methods cannot return other methods (but they can return procs)  
  4. =end  
  5.   
  6. def some_mtd some_proc  
  7.   puts 'Start of mtd'  
  8.   some_proc.call  
  9.   puts 'End of mtd'  
  10. end  
  11.   
  12. say = lambda do  
  13.   puts 'Hello'  
  14. end  
  15.   
  16. some_mtd say  
The output is:
  1. >ruby p025mtdproc.rb  
  2. Start of mtd  
  3. Hello  
  4. End of mtd  
  5. >Exit code: 0  
Here's another example of passing arguments using lambda.
  1. a_Block = lambda { |x"Hello #{x}!" }  
  2. puts a_Block.call 'World'  
  3. # output is: Hello World!