I have just learned how to use a Proc in a simple way. I am going to explain it here and hopefully help someone get a better understanding of them and how to use them.
There are Procs that can be run as ruby methods, along with custom Procs one can create to be reused however many times one would need. Let us use a map enumerable as an example for a Proc.
I have an array that I will call numbers, these numbers will be 10, 20, 30, 40, 50. For this example, I will be adding 2 to every number in the array to get 12, 22, 32, 42, 52. To accomplish this the map would look something like the below.
I have the array.
We will save this to a variable I will call “numbers_array_plus_2”.
Then I will map over my numbers array, using “number” as my stored local variable, and add 2 to that number as I iterate over the numbers array
Now, when I print out my “numbers_array_plus_2” variable in my console I get the below just as I was trying to get.
Now, this is not a lot of code, but this can be shorter by creating a proc. In this situation, the proc is a saved block of code that can be called on as many times as needed. I am going to start this by setting a variable called “add_2” then set it equal to “Proc.new”, followed by the block of code it is to run whenever it is called.
With this “add_2” proc in place, I can now map over my numbers array and do the exact same thing I did with my original map, only I will be calling my proc to help me out. To call this I will still call a map on my numbers array as I normally would, only I will be adding parentheses to my map, and inside of those parentheses, I will have an ampersand symbol (this is your “call to proc”), followed by my proc variable. The below code will yield me the same results as my original map.
As stated before, this is a very simple proc example. The proc block can be any code you will be running more than once and can be very useful in saving time and can be used in conjunction with more than a map. It's a useful tool that I am excited to learn more about.