Last Updated: February 25, 2016
·
588
· pedrolucasp

Transform everthing in an Object with Proc and Lambda

You know that everything in Ruby is an Object. Except for blocs.

You can transform those blocs in objects using the Proc function.

proc = Proc.new do |object|
  puts object.inspect
end

This is the most common way to do this, and then you can call your new object through the call function.

proc.call Object

The method call is used to execute the bloc. In blocs, you can do whatever you want. An interesting case is for sequential processing. In Rails is often used on the definition of named scopes.

The other way is use lambda (<3):

lambda = lambda do |object|
  puts object.inspect
end

Basically, Proc and lambda work in the same way. But there is a little difference, which is about the flux control, in the case return, break, redo, retry, and others, will break your Proc.