- Read Tutorial
- Watch Guide Video
In this lesson, we are going to examine the Proc module in Ruby. At a high level, procs are methods that can be stored inside variables.
Proc Code Example
Let's begin by creating a simple proc.
full_name = Proc.new { |first, last| first + " " + last}
Now, I can call this in two ways. The first is to use the bracket syntax followed by the arguments I want to pass to it.
p full_name["Jordan", "Hudgens"]
I can also use the call
method to run the proc and pass in the arguments inside of parenthesis.
p full_name.call("Jordan", "Hudgens")
Let's go back and retrace the Proc process. In this code, I'm creating a new instance of Proc and assigning it to a variable called full_name
. Procs can take a code block as its parameter, so we are passing two different arguments to it, namely, first
and last
. Since they are arguments, they go inside pipes.
I can do anything I want inside this code block, in this case I'm simply displaying the first and last name. I can also change it to do something like print my first name five times. To do this, I have to modify the code like so:
full_name = Proc.new { |first| first * 5}
We also have another way to create a Proc.
full_name = Proc.new do |first| first * 5 end
This code will result in the same output.
What the block?!
So what exactly is a block? In other programming languages a block is called a closure
. Blocks allow you to group statements together and encapsulate behavior.
There are two ways to create blocks in Ruby and we'll use a Proc to illustrate them.
Curly braces
We'll being by illustrating how to use blocks with the curly braces syntax, as shown here:
add = Proc.new { |x, y| x + y} add[1, 2]
Running this code will return 3
. The code inside of the curly braces is inside the block.
do...end
The alternate way to use blocks is by using the do...end
syntax:
add = Proc.new do |x, y| x + y end add[1, 2]
This will give you the same result as when we used the curly bracket syntax. A rule of thumb in Ruby is to use curly braces when you want to have all logic on the same line. Technically, you can write your program in a single line if you use curly braces.
The next obvious question is: why use Procs when you can use methods to perform the same functionality?
The answer is that Procs give you more flexibility than methods. With Procs you can store an entire set of processes inside a variable and then call the variable anywhere else in your program.