Chapter 1
-
A closure is a function whose body references some variable that is declared in a parent scope.
-
amount is the free variable. This is because amount is not defined in the lambda, but rather, as is_larger_than’s argument.
-
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 complement = lambda do |pred| lambda do |args| not pred.call(args) end end -
The main trick here is that the starting value can be anything you want it to be, including ...
Get Mastering Ruby Closures now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.