Wednesday, September 15, 2010

Use of Proc & proc

Hi

I have used "proc" to run/block validation in model. But now i learned something more about proc.
In ruby, "Proc"(procedure) refers to the block of code, we can reuse it. Block of code assigned to the object.

"Proc" => Starts with capital letter refers to (class name)
"proc" => Refers to the proc object

We can use both the keywords to create a proc by defining any block to them.

below sample code to create a proc and call that proc to execute the block of code

accepts_any_arg = Proc.new{ |a,b,c|
puts "#{a} #{b} #{c}"
}
accepts_any_arg.call(1)
result: 1
accepts_any_arg.call(1,2)
result: 1 2
It just neglects the number of arguments required or passing to that proc, it is working without any argument error. It assigns nil value to arguments which are not passed.


throws_args_error = proc{ |a,b,c|
puts "#{a} #{b} #{c}"
}
throws_args_error.call(1,2,3)
result: 1 2 3
throws_args_error.call(1)
result: Throws "ArgumentError"
it is checking the number of arguments


Thanks,
Vadivelan

No comments:

Post a Comment