Chapter 1
Closing in on Closures

Chances are you’ve heard about closures and tried to find out what they’re all about. You clicked on the first link, which led you to an utterly incomprehensible Wikipedia entry. Your eyes glazed over terms like lexical scoping and free variables, and you started to think maybe you’re just not that smart. If you are in that situation, here’s some great news. This is totally learnable. You just need to learn a few rules and some new terminology.

In this chapter, you’ll learn the rules that define a closure, so you can identify one when you see it. Knowing these rules will also help you understand the more advanced concepts in the rest of the book. Furthermore, you can transfer these concepts to other languages that support closures, such as JavaScript, Haskell, and Elixir.

Once you get comfortable with the basic concepts, you’ll explore two interesting techniques made possible by using closures. First, you’ll learn that you don’t really need classes at all. With some lambdas sprinkled with variables, you can replicate much of the functionality that classes provide. Second, you’ll see how closures let you write decoupled code using callbacks.

Finally, you’ll put this newfound knowledge to use by implementing your own version of Ruby’s Enumerable#reduce method using lambdas, a Ruby language feature that lets you write code in a functional-like programming style.

Once you understand the concepts in this chapter, you’ll unlock other more advanced skills, and once perplexing concepts will become much clearer. Let’s dive in!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18