ap-PROC-simately correct
One day at a time, resisting the urge to be a Block-head…
Being the obedient student that I am, I dutifully watched a Youtube on procs, lambdas and closures as per https://www.thefirehoseproject.com/technical-prep/1 (I didn’t watch Aaron Patterson, couldn’t stand his style).
Here’s what I was able to glean on the topic:
We are used to storing data in variables. You want your program to remember the number 5, so you store it in a variable called i whose value is 5. In a similar fashion, you can store methods in variables and do the same sorts of things as with data. After all, methods are a type of data, right?
So you define a bit of behavior (a block of code) and store it in a proc which is a variable that stores the code and can be told to execute it at will).
my_proc = Proc.new do |a| puts “this is my proc and #{a} was passed to me”end
Whereas only a single block can be passed to a method, you can pass around as many procs as you’d like. The yield method is used inside a method to call whatever block of code is available, i.e. the block that was passed into the method. An error is thrown if there is none. By contrast, a specific proc (say a) may be called by writing a.call.
Proc.new inside a method creates a proc that is automatically initialized to the currently available block unless specified otherwise.
A lambda is like a proc with some subtle differences. Lambdas are more particular about their arguments: an error is thrown is they get too many or not enough. A proc, by contrast, will simply set the arguments to null and execute anyways.
I found the following quite an interesting difference between lambdas and procs: when a proc is called in some context, it actually executes its code in its original context, where it was defined. If, over there, it executes a return statement which exits the program, that’s what will happen. By contrast, lambdas execute in their current context, and will never affect anything more global than where it was called.
Being new to this topic, it seems quite arcane. It’s hard to discern the underlying logic beneath these seemingly arbitrary distinctions and definitions. Nevertheless, the power of anonymous functions as a tool for writing efficient and elegant code is quite apparent, whether in Ruby, Scheme, C, or even Javascript (but in that case, minus the elegance…). Plus, you get to write all sorts of impenetrable one-liners and win points on codewars. Yay! :)