Proc is essentially reusable block. To make a proc, we just add word proc to in front of our block.
For example;
As you can see here we added proc in front of our block and sign it a variable.
crazy_proc = proc { “This is the block that I want to use.” }
when we want to call this proc, we simply do; .call after variable.
crazy_proc.call
When we want to see this in puts;
the last line of picture will give us string “This is the block that I want to use”
Proc take also parameters
When we want to add parameter, we simply add pipe inside the block.
as you can see below picture, we added | |(pipe) and, when we call the variable simply added parameter. add_param.call(“cheese”).
Last thing that I want to mention here;
We could be able to send many or less parameters to a proc, It will still work. When we send less parameters, a proc will assume missing ones are nil. When we send many parameters a proc will ignore the extra ones.
As you can see in above picture, on line 45 I did this;
add_param.call()
without any parameter, Ruby didn’t give any error. It does its work, Ruby accepted that as nil, only out put add_param.call(‘mushroom & onion’)
Here in this below example, I added many parameters add_param.call(“cheese”, “garlic”, “salt”, “pepper”).
This way in many parameters, Ruby only get “cheese” as parameter and ignore the rest.
References