Home » Ruby programming

Procs in Ruby

Ruby Procs: In this tutorial, we are going to learn about the Procs in Ruby programming language with examples.
Submitted by Hrithik Chandra Prasad, on November 14, 2019

Ruby Procs

We have gone through many traditional and conventional things in Ruby but procs is a new thing you will come across. We have seen how we can return value inside the Ruby method but we can also store method inside a variable with the help of Procs. This makes our code more flexible and readable. You can store an entire set of instructions or rules inside a variable and can call them anywhere as per the requirement.

Syntax of Procs:

    variable_name = Proc.new{|argument1,argument2|argument1+argument2}

I think that syntax made you pretty clear about the Procs. Procs can be simply defined with the help of a ".new" method. It requires a block inside which the entire set of the process will be defined. You can specify the argument list inside "||". Now, you will get clearer about it with the help of example which is given below,

var = Proc.new{|num1,num2,num3| num1+num2+num3}

p "The sum is #{var[1,3,4]}"

Output

"The sum is 8"

You can observe in the above code that we have created a proc inside the var variable. The purpose of proc is to calculate the sum of elements entered by the user. These elements are specified inside || and all the processing is done inside the { } block. We are simply calling proc with the help of square brackets and square brackets are having the actual parameters.

Procs are always created with the help of blocks. Blocks always help us to bind the behavior of the statements. There are two ways to create procs which are stated below,

1) With the help of curly braces

We have seen this in the above example where we are creating the proc with the help of curly braces. For your better reference, one more snippet is given below,

var = Proc.new{
	|num|
	i = 1 

	while(i<=10)
		p num * i
		i = i + 1
	end
}
var[12]

Output

12
24
36
48
60
72
84
96
108
120

2) With the help of do end block

procs are also be created with the help of do.. end block. This way makes the code more understandable. Let us understand this with the help of an example. Let us modify the above example in the following way,

var = Proc.new do |num|
	i = 1 
	while(i<=10)
		p num * i
		i = i + 1
	end
end
var[17] 

Output

17
34
51
68
85
102
119
136
153
170

You can call the procs in two ways: one by just writing the name of the variable and the other one is by using the call method. You can use the call method in the following way,

var = Proc.new {|a| a*5}
var.call(12)

Both methods will give you the same results. It is up to you which one you like most.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.