CODEX

Ruby Procs and Lambdas: What’s the difference?

Ward Price
CodeX
Published in
2 min readMar 15, 2021

--

Procs and Lambdas are both used similarly but are different in a particular way. Both are higher order functions which are functions that take other functions as parameters or returns them as a result. Breaking that down further a block is a nameless method that is passed to another method as a parameter.

Blocks cannot be saved as variables. They are one of the few instances in which the ruby “everything is an object” rule is not true.

Procs

Procs are blocks of code that can be bound to a set of local variables. They are essentially a saved block of code.

def foo(x, y, proc_block)
proc_block.(x, y)
end
add = proc { |a, b| a + b }puts foo(3, 6, add) => result is 9

We declare a method foo with the params of x, y and proc_block. x and y will be numbers while proc_block will be a proc.

We then declare the variable add which is a block of code saved as a proc. We declare a proc by declaring it with the word proc then in curly brackets the code we want to run.

Last, we put it all together entering two values and our proc. The result is the sum of 9!

Lambdas

Lambdas come from the class of proc and they look very similar! However, there are small but at the same time big differences between the two. They are anonymous functions so essentially a self executing proc. You can declare a lambda by using the word lambda (old school) or using the ‘stabby’ syntax with a -> . I’ll recreate our proc example from above.

def foo(x, y)
->(x + y)
end
x = 3; y = 6result = foo(x, y).call # or you can invoke using just .()result2 = foo(x, y).()result #9
result2 #2

There is a short high level overview of what a lambda and a proc are!

--

--