Sitemap
Mooventhan

Mooventhan

Proc in Ruby

Jul 30, 2022

Blocks are one of the very few exceptions to the “everything is an object” rule in Ruby. Blocks are not objects, and they can’t be saved to variables.

Get Mooventhan’s stories in your inbox

Join Medium for free to get updates from this writer.

Example code for Proc.

def foo(a, b, my_proc)
my_proc.call(a, b)
end

add = proc {|x, y| x + y}

puts foo(15, 10, add)
output: 25

In this example, we have created the proc add, which adds two numbers.
The proc add is passed as a parameter to the method foo.
In the method foo, my_proc.call(a, b) executes the proc.

--

--