Ruby Procs - Intermediate
Procs tend to be a source of confusion for beginners. If you have been reading each chapter then you already have all the prerequisite knowledge needed to understand procs. Procs provide an object wrapper for blocks. Think of procs as procedure blocks. Proc has a method call that invokes the block, see the example below:
"Smile!" end #<Proc:0x007ff5eb0f7998@(irb):1> happy.call Smile! nilhappy = Proc.new do puts
Why use procs? why not just use methods?
Recall the overarching theme of Learn Ruby First,
#==> "Everything in Ruby is essentially an object, a thing that can be manipulated. These objects are manipulated by methods, sets of expressions that return a value. Everything in Ruby is either an object or a method."
So, what can we do if we want to pass a method into a method or return a method from a method? We simply can't. There is no way in Ruby to do this. Unless, we have an object wrapper for our methods, which then become procs. Then we can pass procs into methods and return procs from methods. This is because procs are objects, methods are not. Once you understand this, working with procs becomes much easier. We could also say, "a proc is a block that you save to a variable". As you can imagine, that variable can then be used as a method argument.