Understanding Procs in Ruby

Ruby provides a way to encapsulate a code block and store it into a variable, which can be passed as arguments to methods. This feature of encapsulating a code block is called Procs. Proc is an essential concept in the functional programming features of Ruby.

Why use Procs?

Procs allow the freedom to choose a design pattern where we can:

  • Dynamically change the behaviour according to the parameters
  • Treat a block of code as an object and assign it to a variable

To be able to dynamically control the flow of execution of a program based on a parameter is a popular choice because the concept of inheritance does not exist in functional programming. So the dynamic execution flow of a program can be controlled using the parameters/data types in runtime. Another helpful design pattern is to send a code block as an argument to a function. For example, Array.sort method accepts the conditional code block as Proc to sort an array.

How to declare a Proc?

Procs can be declared with Proc.new constructor which returns a Proc object and takes code block as input. The code block can be multiline semicolon-separated logic inside curly parenthesis or logic inside do ... end.

# Multiline syntax

# Syntax 1
proc_object = Proc.new { puts "Hello!"; puts "I am a multiline proc."; }
proc_object.call 

# output:
# Hello!
# I am a multiline proc.

# Syntax 2
proc_object = Proc.new do
	puts "Hello!"
	puts "I am a multiline proc."
end
proc_object.call 

# output:
# Hello!
# I am a multiline proc.

Procs can also accept input parameters and perform operations using these parameters, like a method.

square = Proc.new {|x| x**2 }
square.call(3)  # 9 
# shorthands:
square.(3)		# 9
square[3]		# 9

Other various ways of declaring Procs are:

  • Kernel Proc method
proc_object = proc { |x| x**2 }
proc_object.call(2)		# 4
  • Receiving a block of code as an argument
def create_proc(&block)
    block
end

proc_object = create_proc { |x| x**2 }
proc_object.call(2)		# 4

Conclusion

Procs is an essential feature in Ruby, it makes using functional programming paradigm in Ruby convenient and helps a developer control the dynamic flow of execution with parameters. Procs also enable developers to encapsulate a block of code, assign it to a variable and pass it as an argument to a method or another Proc.

Yash Shah

Yash Shah