O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1

  1. A closure is a function whose body references some variable that is declared in a parent scope.

  2. amount is the free variable. This is because amount is not defined in the lambda, but rather, as is_larger_than’s argument.

  3. Here’s one possible implementation:

     new_db = lambda ​do
      db = {}
     
      insert = lambda ​do​ |artiste, album|
      db[artist] = album
     end
     
      dump = lambda ​do
      db
     end
     
      delete = lambda ​do​ |artiste|
      old = db[artiste]
      db[artiste] = ​nil
      old
     end
     
      {​:insert​ => insert, ​:dump​ => dump, ​:delete​ => delete}
     end
  4.  complement = lambda ​do​ |pred|
      lambda ​do​ |args|
      not pred.call(args)
     end
     end
  5. The main trick here is that the starting value can be anything you want it to be, including ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required