> Instances and closures are closely related: an instance is a piece of state with several operations that can be invoked on it, while a closure is a piece of state with one operation that can be invoked on it.
I would go further, and say that they're equivalent—that "one operation" can be a dispatch function:
def make_object
x = 5
lambda do |m|
case m
when 'increment'
x += 1
when 'decrement'
x -= 1
when 'get'
x
end
end
end
o = make_object
o.call('get') # => 5
o.call('increment') # => 6
o.call('decrement') # => 5
I would go further, and say that they're equivalent—that "one operation" can be a dispatch function: