Closures – A Simple Explanation (Using Ruby)

ClosureThere are a great many decent developers out there who don't know what a closure is. I don't really have any concrete stats on this matter, it is simply an intuitive assessment based on experience. But, you know what – that's fair enough, considering that the most popular languages that are in use right now don't support closures (Java, C++). When the language you use day in day out doesn't support a concept, that concept is not going to be high on your agenda; infact you may not even be aware of it. And yes, I agree, good developers will know several (or perhaps many) different languages and there are plenty out there that do support closures – you're bound to stumble across one at some point. Which just goes to show that when most developers learn new programming languages, they go about it completely the wrong way and so when you hear someone say they know a dozen languages, they are likely overstating the situation by quite a margin. But, I'll leave that discussion for another time – today it is all about closures.

You probably came across closures when you were at uni, you just don't remember. Over the last 10 years or so, the curriculum of software related degrees has evolved to the point where concepts like closures are not emphasized, it is predominantly a functional concept and functional languages are out – Java is in. They were trying to make the degrees more industry-relevant and as a result there is a generation of programmers who have been professionally crippled (to some extent) through no fault of their own. You trust the education system to do right by you and there isn't much you can do when this trust is misplaced. I need go no farther than myself for an example. I did Java in the first year of my degree, C in the second. The first time we were exposed to functional programming, was during an AI subject where we had to do some Lisp along with having to learn a whole slew of other concepts. Needless to say, functional programming wasn't the emphasis in that subject; many people struggled and struggled badly. We certainly had some exposure to closures during that subject, but who had time to think about that, it was all most people could do to try and wrap their heads around a new style of programming when they had just spent two years getting used to a completely different one. By the time I found myself in industry, closures – along with most other functional concepts – were long forgotten. It took me years of self-study before I rediscovered this stuff – stuff that should have been the foundation of my education as a software developer. I once had a go at my CS degree for not teaching some things that would have made it more relevant. Were I to write a similar post these days, I would be a lot harsher – I still might.

The bitter irony is that while Java is still well and truly in, the functional style is coming back with a vengeance. Fully functional languages (Clojure) and functional hybrids (Scala) are in vogue and so the concepts that underpin them are once again relevant. But, the damage has already been done and will continue to be done – academia does not adjust itself in a hurry. You can't afford to be ignorant of functional concepts any more, even JavaScript – that Web 2.0 language that we all love to hateis a functional hybrid. And so developers scramble to get their heads around these concepts and as they scramble they are presented with stuff like this:

"In computer science, a closure is a first-class function with free variables that are bound in the lexical environment."

What the hell does that even mean! Wikipedia does go on to explain it a little bit better, but without some functional context, it is still tough going. Here is another one you commonly hear:

"A closure is a function that is said to be "closed over" it’s free variables"

Really! A 'closure' closes over, why, that makes it all much clearer. Seriously, the next question is always bound to be a plea for clarification. An explanation like that is worse than no explanation at all, although it certainly does make someone sound smart. But, when you're trying to teach someone something it is not about self-aggrandisement – we can do better. Let's give it a go.

A Concept Explained Simply

A closure is basically a function/method that has the following two properties:

  • You can pass it around like an object (to be called later)
  • It remembers the values of all the variables that were in scope when the function was created. It is then able to access those variables when it is called even though they may no longer be in scope.

Let's fill in some more details. As you may have guessed, you don't get closures for free; they must be explicitly supported by the language. In order for the language to be able to support closures, it must support first-class functions. A first class function is a function that can be treated like an object in that you can store it in collections and pass it as a parameter to other functions. As I said, the ability to be passed around is the first property of a closure.

A normal function is defined in a particular scope (i.e. in a class) and can only be called within that scope. This function has access to all the variables in the scope that it is defined, like the parameters that are passed into it as well as class variables. A closure on the other hand may be defined in one scope and be called in a completely different scope (since we can pass it around before calling it). Because of this, when a closure is created, it retains the values of all the variables that were in scope when the closure was defined. Even if the variables are generally no longer in scope when the closure is called, within the closure they still are. In other words, the closure retains knowledge of its lexical environment at the time it was defined.

Hopefully that "lexical environment" sentence above is starting to make a little bit more sense now, but I am sure it would make a lot more sense if we had an example. 

An Example In Ruby

No explanation is complete without some examples, that is usually what it takes to make things start to fall into place. We will use Ruby since it supports closures and I like it.

In Ruby, closures are supported through procs and lambdas. These constructs are very similar, but there are some subtle differences (I might do a post about that soon). Let's create a closure and see how it fulfils the two properties described above.

class SomeClass
  def initialize(value1)
    @value1 = value1
  end
 
  def value_printer(value2)
    lambda {puts "Value1: #{@value1}, Value2: #{value2}"}
  end
end
 
def caller(some_closure)
  some_closure.call
end
 
some_class = SomeClass.new(5)
printer = some_class.value_printer("some value")
 
caller(printer)

When we execute we get the following output:

alan@alan-ubuntu-vm:~/tmp$ ruby closures.rb
Value1: 5, Value2: some value

As you can see, the value_printer function creates a closure, using the lambda construct, and then returns it. We then assign our closure to a variable and pass that variable to another function, which then calls our closure. This satisfies the first property of a closure – we can pass it around. Notice also that when we called our closure, we printed out "5" and "some value". Even though both the @value1 and value2 variables were both well and truly out of scope in the rest of the program when we finally called the closure; inside the closure they were still in scope as it retained the state of all the variables that were in scope when it was defined. And so, our lambda satisfies the second property also which makes it a closure. I hope the example has made things a bit clearer.

Of course, we can look into closures a little bit more deeply. For example, how do they retain the values of the variables that were in scope when the closure was defined? This must be supported by the language and there are two ways to do that.

  1. The closure will create a copy of all the variables that it needs when it is defined. The copies of the variables will therefore come along for the ride as the closure gets passed around.
  2. The closure will actually extend the lifetime of all the variables that it needs. It will not copy them, but will retain a reference to them and the variables themselves will not be eligible for garbage collection (if the language has garbage collection) while the closure is around.

If the language supports the first way, then if we create two or more closures which access the same variables, each closure will have its own distinct copy of those variables when it is called. If a language supports the second way, then all closures will reference the same variables, i.e. they will in effect be dealing with exactly the same variable. This is how Ruby does things. Here is an example:

class SomeClass
  def initialize(value1)
    @value1 = value1
  end
 
  def value_incrementer
    lambda {@value1 += 1}
  end
 
  def value_printer
    lambda {puts "value1: #{@value1}"}
  end
end
 
some_class = SomeClass.new(2)
 
incrementer = some_class.value_incrementer
printer = some_class.value_printer
 
(1..3).each do
  incrementer.call
  printer.call
end

This produces the following output:

alan@alan-ubuntu-vm:~/tmp$ ruby closures.rb
value1: 3
value1: 4
value1: 5

We create two closures this time, one to increment a value and the other to print it out. When we then call both of the closures three times, we can see that both are operating on the same variable as the value is incremented on every iteration. If Ruby handled retaining variables for closures by copying them, we would have had the original value of 2 printed out on every iteration since our incrementer and printer closures would each have had a distinct copy of the @value1 variable.

Why Are Closures Useful

Closure

Now that we understand closures a bit better, what's the big deal about them anyway? Well, it depends on what kind of language you're using. In a functional language they are a very big deal. Functional languages are inherently stateless, but we can use closures to essentially store some state which will persist as long as our closure lives on (i.e. if the closure changes the value of a variable it will retain the new value the next time the closure is invoked). I hope it is reasonably self-evident how this can be useful. The existence of constructs such as closures along with several others, allow functional languages to be very terse in expressing logic which means you can do more with less code.

With non-functional languages things are a little murkier. There are better ways to represent state when it comes to imperative languages, so the only thing that makes closures compelling in that situation is the fact that you can use them to write terser code while still taking advantage of the imperative style. The existence of closures is partly the reason why people can often do more with less code in languages like Ruby (which support closures) than they can in languages like Java (which do not). If you have other things to add about the awesomeness of closures in any context, then do leave a comment, the more information we share the better off everyone will be.

Images by Tattooed JJ and ~Oryctes~ (Off)

  • http://reprog.wordpress.com/ Mike Taylor

    Let me just drop in a plug for my own article Closures, finally explained! over at The Reinvigorated Programmer. I covered similar material in a different style — people new to closures might find it useful to read both.

    • http://www.skorks.com Alan Skorkin

      Hi Mike,

      No worries, I am a big believer in approaching any concept from different angles. I still periodically like to go back to basic concepts, I find I get a little bit more out of it every time due to experience and a fresh perspective and my understanding is enhanced every time. When you understand the fundamentals a little bit better, everything else is improved as a result.

      I like it how we both found that Wikipedia sentence almost nonsensical, chances are if two people find it so there are a million more out there in the same boat.

      • http://starjuice.net/ Sheldon Hearn

        I do hope you’ll edit the Wikipedia article.

        Ciao,
        Sheldon.

        • http://reprog.wordpress.com/ Mike Taylor

          Someone did edit the Wikipedia article shortly after my article was published, but the change was quickly reverted.

          • http://www.skorks.com Alan Skorkin

            Which makes me think that you have to be part of the Wikipedia in-crowd if you want to make a change and have it stick.

          • anonymous

            The edits Mike refers to were reverted because Wikipedia is not a textbook and informal explanations should be added with care. The explanation which is in the article makes sense if you know what “free variables” are and describes closures in their full generality. The further points about shared state, information hiding, garbage collection etc. are language-specific and do not apply to languages such as Haskell or ML in which variables are captured by value and references are a separate concept.

            Signed, someone in the “inner crowd” of Wikipedia whose edits stick.

          • http://www.skorks.com Alan Skorkin

            Hey anonymous,

            Hehe, point taken. You’re probably right, Wikipedia has a certain style to its entries and it is probably best to maintain that style at this point in time. I guess, I am just not a big fan of explanations that don’t stand up on their own. It is fine for an explanation to raise more questions, but it shouldn’t require you to understand those extra questions before you can grok the original explanation. I suppose this is why I wrote a post about closures rather than just tweeting in a link to the Wikipedia entry.

  • http://fractalcomposer.com Myron Marston

    I love closures, but I often find that it’s very difficult to explain why they are so useful. I think they are one of those concepts that don’t seem that useful until you’ve used them a fair amount.

    I think my favorite thing about closures is that they allow you to add behavior to any chunk of code (hmm, maybe that isn’t the best way to phrase that, but I can’t think of a better way). For example, with RSpec you pass a closure to #before(:each) to cause your closure to be run before each example. You pass a closure to #let to define an instance method that is automatically memoized. With Cucumber, you pass a closure to Given, When or Then to define a step.

    This kind of power and flexibility simply isn’t possible in a language that doesn’t support closures. You can kinda get some of the flexibility with a feature like C#’s attributes, but the syntax is not nearly as nice, and closures will always be more flexible.

    • http://www.skorks.com Alan Skorkin

      Hi Myron,

      I think you’re right. I alluded to it in the post. But it definitely helps to have more context in a closure-rich language before you truly grok closures. I think this is true for many different concepts which is why I sometimes like to get a high level overview and then go and use something for a while with the intention of then coming back to it several times as my experience with a language grows.

    • Nik

      Myron, you don’t have to fake with attributes, C# provides closures via anonymous delegates

  • James

    Hey,

    I’ve been looking into Procs recently, so this post caught my attention. I looked at your second example, though, and didn’t really see why I would want to use a closure here when it’s a simple feat to use a regular class:

    class SomeClass
    def initialize(value1)
    @value1 = value1
    end

    def value_incrementer
    @value1 += 1
    end

    def value_printer
    puts “value1: #{@value1}”
    end
    end

    some_class = SomeClass.new(2)

    (1..3).each do
    some_class.value_incrementer
    some_class.value_printer
    end

    value1: 3
    value1: 4
    value1: 5

    and receive exactly the same result. What’m I missing about closures that makes them useful in ruby?

  • James

    Oh! Now I see! You have two different variables sharing the same internal context!

    Interesting.

    • http://www.skorks.com Alan Skorkin

      Hi James,

      My example was very contrived, both of them infact. You certainly don’t NEED closures for it, however once you understand the implications of what is happening then some concepts become clearer. For example methods like, select, collect, inject, reject in ruby allow you do a whole lot of stuff with very little code. These are basically higher order functions, and all of this is possible due to the language supporting closures. I will likely do a post on those methods at some point which will hopefully make things a little clearer regarding closures as well.

      • http://www.blogger.com/profile/10430235452297873953 Andrei Vajna II

        Yep, very good examples. You definitely should write a post wtih such examples.

        That makes me think. “Closure” is perhaps a too technical term. They are just first-class functions. You don’t need to explicitly think of a closure when you’re doing your program. You just start writing the lambda, and when you’re finished you realize “Hey, I’m also using a free variable here. This is a closure.” You don’t need to think about it, because it just works. You don’t need special syntax to differentiate betweene an ordinary lambda and a closure. (Except maybe the “final” modifier in Java) Like Mike Taylor wrote in his article, he was happily using blocks and then he realized they were actually closures. But he could have esily not made that remark and he still would have been a happy programmer.

        Of course, there is a big difference when you get deeper. When you write the compiler you need to make this difference, because in the case of the closure you need to take special measures to embed the local environment in the closure. But as a normal programmer you might not need to know this. Of course, if you respect yourself, you need to understand what’s going on. But that’s why I said it’s a too technical term.

  • http://passingcuriosity.com Thomas Sutton

    On the subject of education, I agree 100%. The fact that someone can graduate from a CS programme without knowing knowing about closures is perhaps a sign that it isn’t a CS programme.

    I’m not sure about your basis for objecting to the Wikipedia description (Wikipedia is not, after all, a tutorial!) That first paragraph concisely describes closures using the language of the field. Each of the terms in that first few sentences — first-class function, free variable, bound, lexical environment, “closed over”, scope, lifetime — are all essential to the understanding of the concept. Indeed, I would argue that an explanation that doesn’t use those terms is worse than no explanation at all: it breaks the links between closures and other, related, concepts. You can’t properly understand closures without also understanding those concepts *and* the terminology they are usually couched in.

    I would add to the benefit of terseness that you mention information hiding and specialisation.

    Using closures, you can hide information from other code, even in the face of open classes, introspection and similar language features. Wrapping your state up within a closure ensures that no-one else can stomp on it. This pattern is quite common in Javascript (in plugins for jQuery, for example).

    Faking partial application to specialise functions is probably included in your terseness point, but I think is sufficiently cool to bear repeating. You can write a function (called `partial`, for example) that accepts a function and a few arguments and returns a closure which accepts the rest of the arguments (if any), calls the function, and returns the result. This can help reduce the amount of state threaded through the application, lets you write generic code (to be optimised as and when required), etc.

    function sayMessage(name, msg) { console.log(name+” : “+msg); }
    var tellDave = partial(sayMessage, “Dave”);
    var tellJulia = partial(sayMessage, “Julia”);
    tellDave(“I’m afraid I can’t let you do that.”);
    tellJulia(“Boo!”);

    In any case, thanks for another great article on an interesting topic.

    • http://reprog.wordpress.com/ Mike Taylor

      I’m not sure about your basis for objecting to the Wikipedia description (Wikipedia is not, after all, a tutorial!) That first paragraph concisely describes closures using the language of the field. Each of the terms in that first few sentences — first-class function, free variable, bound, lexical environment, “closed over”, scope, lifetime — are all essential to the understanding of the concept.

      It seems pretty obvious to me that a definition of closure that needs to use the phrase “closed over” is not going to be useful to anyone who doesn’t already know what a closure is (and since no definition is useful to someone who already knows what the defined term means, it follows that it’s useful to no-one at all).

      In fact, you don’t need to know the meaning of any of those terms to understand that

      (1..10).each { |i| someFilePointer.puts i }

      works, and to be introduced to the notion that the block between the braces can see the variable someFilePointer from outside it.

      • http://passingcuriosity.com Thomas Sutton

        Yes, but that isn’t (just) a definition. It’s the introduction of an article in a hypertext encyclopaedia. If this were the single sentence in a dictionary definition, then I’d agree whole heartedly, but I don’t think it out of line to use technical language in an encyclopaedia article (especially when most of it is hyperlinked).

        Sure, anyone can see that it works. But they haven’t understood it until they’ve seen beyond that example (not a particularly powerful example of closures) to understand that the lifetime of the closure can go beyond the lexical scope of the variables it is capturing (“closing over”, even) and it will *still* work. They need to understand that the “free variables” in the “first-class function” are “bound” with values from the “lexical scope”, even thought the function itself may exist after that scope has been exited. I think it is important that people do, in fact, learn and use those words; in the same way they learn the jargon of OO programming or anything else.

        But I agree that the Wikipedia article certainly doesn’t stand on its own without either background knowledge or reference to a number of other articles.

    • http://www.skorks.com Alan Skorkin

      Hey Thomas,

      I am with Mike regarding the Wikipedia point. I do believe that the example you give is an example of currying which is only made possible through closures :). Another one of those concepts which is often badly explained, thanks for highlighting it.

  • lee doolan

    You said:

    “There are a great many decent developers out there who don’t know
    what a closure is. ”

    I find this somewhat hard to believe, actually. I was recently on the job market for a period of 8 months. I had what seems like 100 or so phone interviews and 25-35 in person interviews over that time. I would say that a large majority of interviewers asked me to define the term ‘closure’. Another very popular such term was ‘polymorphism’, and a third was ‘left join’. Many people asked this question in some form:

    “There are a number of HTTP methods, GET is one. Name two more.”

    The above question is popular with HR representatives who are non-technical. I sometimes envision them with a 3×5 card next to their phone with this list:
    OPTIONS
    GET
    HEAD
    POST
    PUT
    DELETE
    TRACE
    CONNECT

    If you are interviewing, it is a good idea to be able to define a number of such terms succinctly perhaps with a clarifying example.

    • http://www.skorks.com Alan Skorkin

      Hi lee,

      The concept is in vogue now which is probably why everyone is asking the question, it doesn’t mean that many people are able to answer it or even when they do answer it they may not really understand it.

  • Svend Tofte

    Closures are nice for the same reasons as stateful objects are in OO languages. They represent partial computations (the closure may or may not be stateful, depends on the functional language undernearth). It’s like parameters to an object, that specialize it, and closures allows the same basic thing.

    • http://www.skorks.com Alan Skorkin

      Hey Svend,

      That’s a very succinct summary, I like it.

  • http://pierrespring.com Pierre Spring

    Can I just plug my recent article that explains lexical scoping (aka closure) in JavaScript. Maybe this is of interest to someone ;)

    http://pierrespring.com/2010/05/11/function-scope-and-lexical-scoping/

    • http://www.skorks.com Alan Skorkin

      You certainly can :), like I said, the more different points of view the better.

  • Stefan

    Very good explanation, thanks!

  • http://www.blogger.com/profile/10430235452297873953 Andrei Vajna II

    As a matter of fact, I do have an interesting and conrete example of the usefulness of closures.

    Just yesterday, I was working on a project for school, in which I had to implement the Simulated Annealing algorithm. A step is to select a random solution from a so called neighbourhood of the current solution. At first, I simply generated all solutions in the neighbourhood, and selected a random one from the list. Now this is quite inefficient, because you discard all the other solutions. You’ve generated them for nothing.

    What I did, was that instead of adding the generated solutions to the list, I added closures that generate that specific solution. It’s what is known as a delayed list. This way I only execute that code once, when needed. And this was an almost 2x improvement. Closures rock!

    And it was only a simple change. I replaced (C# code)

    neighbourhood.Add(GenerateSolution(i));

    with

    neighbourhood.Add(() => GenerateSolution(i));

    • http://www.skorks.com Alan Skorkin

      Hi Andrei,

      Very nice and definitely a good use case for closures.

  • Pingback: Closures – A Simple Explanation (Using Ruby) via Skorks - The Agnostic Coder

  • Ramkumar

    Very good Closure – 101 article. Thank you very much.

  • http://www.michaelmerino.net Michael Merino

    Hi Alan,

    Thanks for the great article on closures. I seem to recall that Java will be implementing closures in Java 7. So I’m sure this will be a topic of greater interest. I’m glad you brought it up.

    Though you may have spent a bit too much time spent explaining why we don’t know about closures and too little time explaining how they are useful. :)

    • http://www.skorks.com Alan Skorkin

      Hey Michael,

      Haha, yeah I guess it wasn’t just about explaining closures, but also a vehicle for self-expression :). I’ll do a few more posts in the future doing a quick explanation of some of the other concepts that are supported by closures which should make their utility apparent.

    • http://reprog.wordpress.com/ Mike Taylor

      Michael Merino wrote: “I seem to recall that Java will be implementing closures in Java 7.” Apparently (and rather lamely), it seems not. See http://www.davidflanagan.com/2010/05/closures-in-jav.html

  • http://www.michevan.id.au/ Evan

    > it is predominantly a functional concept

    Would be interested in future articles that cover functional programming generally, not just closure specific. Good work as always.

    E.

    • http://www.skorks.com Alan Skorkin

      Hey Evan,

      Luckily, I do have plans to cover some more functional concepts, although it will be in Ruby for the moment (as opposed to scheme or haskell or some other fully functional language) :).

  • oren

    what a clear and fun explanation for a complex topic.
    thank you Alan!

  • Pingback: Closure in JavaScript – with examples « tinyHippos

  • Scott

    Thanks for the explanation of closures. I’ve been looking for a coherent explanation without so much jargon. I agree that the Wikipedia article leaves a lot to be desired for someone who is coming from a non-functional programming background.

    I agree that proper terminology can be useful to someone who knows all the terminology. I’m sure it has more precise meaning and nuance than a general explanation would.

    On the other hand, the person with the additude saying a general explanation is worse than no explanation at all needs to realize that not everyone is a subject expert in every subject. Even those that are experts do not start out that way. In fact, I pretty much guarantee if he holds his doctor, architect, accountant or mechanic to the same standard he insists on (of only using the most precise jargon with everyone and at all times), then he’s going to have some troubles. It’s an obviously ridiculous assertion that the only useful explanation is a complete and jargon-filled one.

    A “good enough” simplified explanation is useful in many contexts even if it’s not 100% accurate or nuanced. It allows a “way in” to a subject. If someone’s serious about it, they’ll eventually come to understand all the terms around it and get the nuance, interconnections and application. But no one begins life by knowing everything about a subject.

    I appreciate the ‘tude-free explantion, which is exactly why this post is really useful, since some of us are still in the process of learning and didn’t spring from the womb fully knowing everything.

    • http://www.skorks.com Alan Skorkin

      Hi Scott,

      That’s exactly how I feel, which is why I like to write these kinds of posts :).

  • Pingback: Closures (clausuras) | malev's blog

  • Sean

    Thank you for this excellent article. I’ve been a developer for many years, and started with RoR only four or five years ago. I’ve been happily writing RoR applications for small clients for quite some time now, while working on .NET in the corporate environment.

    Now comes the time when I need to find a new primary contract– preferably in RoR, which is where my newer experience lies.

    Immediately, I’m barraged by questions on “closures”, “lambdas” and the like. I’m hit with statements like: “How can you be properly refactoring your code if you don’t know what closures are??” Needless to say, I haven’t gotten those positions.

    @Thomas: The Wikipedia article was next to worthless to me. Also not being born fully “functionally” aware, the definition statement was completely foreign. Oh, and by the way, I consider myself an excellent developer, and have been writing high quality, easily maintainable code for a little over two decades now (which means my CS degree is somewhat dated). My problem is: I’ve been too busy solving business problems and providing software solutions, and not enough time keeping up on the latest developments in the underlying language.

    I’m rectifying that shortcoming now– and articles like yours are proving extremely valuable

  • http://blog.mostof.it/ Ochronus

    Thanks for the post! I’ve also written an article about Ruby blocks and closures with code examples. It has a bit different view on the subject, so I think your readers will find it useful.

  • Mike

    Excellent post! On a positive note, though, maybe academia *is* catching up somewhat. I think the concept is definitely taught to a satisfactory degree. It was the only thing we covered in the first 2 months of my CS education (first class functions, lexical and dynamic scoping, etc).

    Like @Thomas said I would argue that what’s important here is to learn those concepts (and sometimes the jargon that comes with it), after which the definition that a closure is a “first-class function with free variables that are bound in the lexical environment” is no longer so cryptic.

  • Greg

    Okay, I know I’m about a year late on this post, but I have to comment.

    This was incredibly helpful to my understanding of this concept. I spent two years at a university studying computer science, and I learned a lot while there, but I had never heard of this. Recently, while writing some JavaScript code and trying to wrap my mind around how to write an event handler that would accept additional arguments yet still give access within to the “e” object, I received help in the ##javascript irc channel in which an example of a closure was given to me.

    I stared at it for five minutes, never having seen such a beautiful piece of javascript in my life, and unable to comprehend it immediately. After working through it for a few minutes, it dawned on me what was happening, and I was amazed.

    This article has improved my self-learned understanding. I feel as if a window has been opened, and my soul refreshed in some way.

    Semi-serious melodrama aside, thank you again for writing this; it was a great help :D

  • http://amiralles.com.ar amiralles

    Great post!!!
    This is awesomeness!!!

    “■You can pass it around like an object (to be called later)”
    “■It remembers the values of all the variables that were in scope when the function was created. It is then able to access those variables when it is called even though they may no longer be in scope.”

  • http://altbit.org Christopher M. Hobbs

    Great post! I could’ve used this explanation years ago. I agree 100% with your comments about college as well.

  • Pingback: Closures: Links, News and Resources (1) « Angel “Java” Lopez on Blog

  • Pingback: Ruby: Links, News and Resources (2) « Angel “Java” Lopez on Blog

  • http://sinceivebeenbloggingyou.blogspot.com Imanol

    I have an exam in a few hours and I still didn’t have this concept clear enough… Now I think I do. Thanks buddy!

  • Christian Ramón R.

    Great article, thanks for sharing knowledge dude.

  • Elwood

    Excellent article. I have to confess to being one of those guys left a little dazed by the wikipedia article. Thanks very much, I feel like a light just went on!

  • http://twitter.com/cybermaster Bill Zhao

    In your first example, you should clarify this sentence a little more. “We then assign our closure to a variable and pass that variable to another function, which then calls our closure.” Propose change: We then assign our closure to a variable (printer) and pass that variable (printer) to another function (caller()), which then calls our closure. It will be easier for people to understand explanation. However, overall this is the best article that I have read related to closure. Thank you very much for sharing this!

  • http://www.webkitchen.co.uk petenixey

    I just wanted to say that I’m a longtime reader and referrer to your site but also a dweller. Your writing however is extraordinarily useful and offers excellent insight into Ruby. Thank you for taking the time.

  • dineshswamy

    great post … and thankyou …

  • http://twitter.com/lee_hosang 호상

    Amazing post. Thank you very much for all the detailed information regarding closures.

  • http://twitter.com/aokolish Alex Okolish

    Thanks a lot for this post. It really helped me understand the concept.

  • tbys

    Thanks a lot. This is the best explanation I have read so far. I agree that the Wikipedia definition does not provide a good conceptual introduction to closures.

    If possible, I would like you to go a bit into details with what happens when the original variable falls out of scope.

  • http://twitter.com/Suchitra_E Suchitra Edussuriya

    Serendipity! You teach well. I am new to Ruby and learning to appreciate all it can do. This will be very helpful.

  • Nathan

    very well written – thankyou

  • Enrique

    Einstein once said, “If you can’t explain it simply, you don’t understand it well enough.” This guy understands. I have never encountered such a concise, thorough, explanation of such a difficult topic. Alan makes this so easy. THANKS

  • Pingback: Closures in Ruby – Part1 | Ruby on Rails

  • Dhanabal

    Thanks a lot for your clear explanation :)

  • Pingback: Closures in Ruby – Part2 | Ruby on Rails

  • nonameanon

    half of your text is nagging on others for you to look more clever…

  • Adam

    I never and I mean never comment on people’s blogs. But for once I have to say THANK YOU!
    That was very helpful!!!!

  • Pingback: Why Ruby Procs are Closures | Ruby/Rails Programming

  • Hélio Rugani

    Thank you a lot. Good job.

  • rob

    This helped me understand how to do closures in Ruby but this bugged me:

    “Functional languages are inherently stateless…..I hope it is reasonably self-evident how this can be useful.”

    Because you said this:
    …..”An explanation like that is worse than no explanation at all, although it certainly does make someone sound smart.”

    Im afraid it is not self evident and I have yet to understand what closure achieve that traditional constructs do not (apart from some gain in “elegance” at the cost of readability)

  • Randy

    Java has supported closures for a long time with the final keyword. Get your facts straight!