Tuesday, May 22, 2012

Procs in rails 3

Proc is an object of code blocks that are assigned into variable.Proc and Blocks are same, but the primary difference is performance.

def say_message_with_name(message) Proc.new do |name| message + " " +name end end
message1 = say_message_with_name("Good morning") message1.call("Tom")
In this example, simply show message with name. Proc is created when constructor is called and given a block as a parameter

The code in the block is treated as Proc instance and can be called any time.You can call Proc code block anytime using "call" method

Output of above example

1.9.3p0 :011 > def say_message_with_name(message) 1.9.3p0 :012?> Proc.new do 1.9.3p0 :013 > |name| message + " " +name 1.9.3p0 :014?> end 1.9.3p0 :015?> end => nil
1.9.3p0 :016 > message1 = say_message_with_name("Good morning") => #<Proc:0x8e8382c@(irb):12> 1.9.3p0 :017 > message1.call("Tom") => "Good morning Tom"

Purpose of Proc

If you want to create a block of code and pass it around on you're application or generate new blocks from existing block.

No comments:

Post a Comment