Ruby Quiz (Advanced) #1

question mark

Question

What will be the output of the following code snippet?

[gist https://gist.github.com/cawel/5ac7b7f28fa5ad80a7b0]

 

Solution

The output is 3, and not 300 as one might expect. The reason for this is in the nature of the Proc object, and thus how it deals with the return keyword. Contrast it with using a lambda instead of a Proc object in this case, which would this time return 300:

[gist https://gist.github.com/cawel/3b63df6bf59d71fafc95]

Robert Sosinski eloquently details the differences between Proc and lambda (which I adapted to fit to my code snippet above):

The answer is in the conceptual differences between procedures [using Proc objects] and methods. Procs in Ruby are drop in code snippets, not methods. Because of this, the [return statement in the Proc object in effect overrides the] method’s return, and acts accordingly. Lambdas however act just like methods, as they check the number of arguments and do not override the calling method’s return. For this reason, it is best to think of lambdas as another way to write methods, [in] an anonymous way. – Robert Sosinski

If you’re interested in learning more about blocks, Proc‘s and lambda‘s, Robert Sosinski has written the best article I have read on the topic so far.

Advertisements

Got a comment?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: