February 27, 2015 by Daniel P. Clark

Value Assignment and Deferment with Lambdas/Procs

When assigning a variable with a raw value the outcome is as you would expect.

Now while learning about assigning methods to variables I used to wonder if I was assigning the result value from the method, or simply pointing to the method to be run when the variable was called upon.  To show what happen I will use Time.now for the method being assigned to the value since it changes every second.

As you can see the variable x saved the value from Time.now and didn’t call the Time.now method when accessed later.  To show that this is a method being called I’ll show the same done from a block and a method.

As you can see a regular block and method run once when being assigned to a variable and the variable stores the value itself.  Well what if you wanted the variable to always get the value by running the method?

Deferred with Lambdas and Procs

When you assign either a lambda or a proc to a variable then it is available to execute later.  The one thing to note is that you will need to use either .[] or .call methods on the variable to execute the lambda/proc.

So now the code we want to run when we access the variable runs each time.  Each of these can also be assigned to a constant within a class.

With this you see the same rules apply.  But what I think is really cool is now you can see a class constant also work as a method with lambdas and procs.


This was a short one.  I only recently came across the ability to have constants be methods you could call.  I really like using lambda in this way.  I’ve decided to use lambda constants for internal methods in my PolyBelongsTo project.  So they are methods available in the project, but their purpose was for internal use.  Methods I’ve intended for more general use are standards methods and easily accessible.  The reason I chose to go about it this way is that it’s a bit unusual to see a constant lambda out in the wild.  So I felt that would be more of an intention indicator.  Yes I know; it defies the very meaning of the word constant.  I expect there may be some people who may be adamant against this kind of use of constants in open source.  You’re more than welcome to share why it’s important to you.  For me, I’m just a Ruby programmer enjoying the beauty and flexibility that Ruby gives me.

If you haven’t been using lambdas and procs yet then I believe that this shows you some of the value they provide.  There are times you need to defer work to be done.

Have fun!  Please feel free to comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

Image by David via the Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic License.