Holla Tech - Learn

Procs
 

Ruby provides the ability to take a block of code, wrap it up in an object (called a proc), store it in a variable, and run the code in the block whenever you feel like (more than once, if you want).
For example: 

greet = Proc.new do |x|
  puts “Welcome #{x}”
end 

 

We created a Proc that takes a parameter and outputs a greeting, and assigned it to the greet variable.
We run the code in the proc using the call method.

greet.call “David”
greet.call “Amy”

# Outputs
# “Welcome David”
# “Welcome Amy” 

 

NOTE!
The code between the do and end keywords can include any number of operations.

Procs
 

Procs are very similar to methods. They perform operations and can include parameters.
What make Procs really powerful and unique is the ability to pass them into methods, because procs are actually objects.
For example:

greet = Proc.new do |x|
  puts “Welcome #{x}”
end

goodbye = Proc.new do |x|
  puts “Goodbye #{x}”
end

def say(arr, proc)
  arr.each { |x| proc.call x}
end 

 

We have defined two procs and a method, that takes an array and a proc as its parameters. For each item in the array it calls the proc. Now, greet and goodbye are objects that contain the corresponding blocks of code.
We can call the say method and pass our proc objects as parameters:

people = [“David”, “Amy”, “John”]
say(people, greet)
say(people, goodbye

 

We can pass to our methods as many procs as we want.

NOTE!
Using procs gives the added flexibility to be able to reuse code blocks in more than one place without having to type them out every time. Procs basically take blocks of code and embed them in an object, allowing them to be reused and passed around.

Procs
 

Let’s create a program that counts the execution time of a block of code.
We will define a method that takes a proc as its parameter and counts the time it takes to execute the proc.

def calc(proc)
  start = Time.now
  proc.call
  dur = Time.now start
end 

 

Let’s see it in action:

someProc = Proc.new do
  num = 0
  1000000.times do
    num = num + 1
  end
end

puts calc(someProc

 

NOTE!
With that tiny calc method, we can now easily calculate the execution time of any Ruby code!

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE. 

RUBY MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT