Blocks, Procs, and Lambdas

Nichole Shelton

December 6, 2014

Today we'll review the differences between Blocks, Procs, and Lambas. What are these things? Programmers call them closures. What's a closure? It's a way to organize code that you want to run in a program.

Blocks

So the first thing that I learned about Blocks that literally blew my mind is they aren't objects! What!!!!!!! Everyone boasts that everything in Ruby is an object. LIARS. Blocks are the exception. Go ahead...look it up, take a deep breath, and come back. Blocks are code that you add into a method as input. You can use blocks in methods with curly braces {} for one line methods or do..end for two line methods. Blocks take input, return information (using return), and use methods like each, map, collect, sample, and a host of others. You can only pass one block per argument list. Also, you have to type out a block each time you use it. Feel the arthritis in those digits? Let's look at the code shall we?

[0, 1, 2, 3, 4].each {|num| print "#{num}!"}
#=> 0!1!2!3!4! => [0, 1, 2, 3, 4]

[0, 1, 2, 3, 4].each do |num|
print "{num}!"
end
#=> 0!1!2!3!4! => [0, 1, 2, 3, 4]

See, same output.

Procs

What's a proc you might ask? Procs are objects (ahhh normalcy). With a proc you can ...wait for it.... save your block to a variable and use it later, thus making it more permanent. OMG that's sexy. Additionally, you can call multiple procs to methods. When using procs, you create them similar to the way you create a new Class. In our example, after we create the new proc, we'll use that block of code as an input function. Let's check it out.

def multiple_procs(proc1, proc2)
proc1.call
proc2.call
end

a = Proc.new { puts "I love procs!" }
b = Proc.new { puts "I'm all about procs!" }

multiple_procs(a,b)

#=> I love procs!
#=> I'm all about procs!

Lambdas

Last, but certainly not least, we have the lambdas. Lambdas are like cousins to procs, but let's be clear: both are Proc objects. There are 2 differences: 1) lambda checks the number of arguments it receives and returns an argument error if they do not match; 2) When lambdas encounter a return statement, it returns their value to the method. Lambdas are pretty flexible about what it allows you to return. Below, we'll look at the differences between procs and lambdas

def proc_math
Proc.new { return 1 + 1 }.call
return 2 + 2
end
def lambda_math
lambda { return 1 + 1 }.call
return 2 + 2
end

proc_math # => 2
lambda_math # => 4

Conclusion

My goodness we covered a bit. Let's review

Happy coding!