From: Clemens Hintze Date: 2000-12-29T22:10:02+09:00 Subject: [ruby-talk:8255] Re: what is meant by ruby's closure? >>>>> "Phil" == Phil Mitchell writes: Phil> The ruby language comparison page emphasizes that Ruby has Phil> better closure feature than python. What does this mean? I Phil> know what closure is in the mathematical sense, but for a Phil> programming language...? A closure is simply some nameless code wrapped together that happens to remember the environment/context it was created in; it is regardless whether the context is already left! Please look at this: def closure_gen(value) getter = lambda { value } setter = lambda { |newval| value = newval } return getter, setter end clos1get, clos1set = closure_gen(12) clos2get, clos2set = closure_gen(14) p clos1get.call # => 12 p clos2get.call # => 14 clos1set.call(15) p clos1get.call # => 15 p clos2get.call # => 14 You can see here that in the context of method closure_gen there are three method-local variables created: 1. value (the argument to the method) 2. getter (reference to closure simply returning the value of 'value') 3. setter (reference to closure setting 'value' to a new value The closures referred by getter and setter are returned to the caller. The context of closure_gen is left but still alive as the closures referred by getter and setter remembering it. As the closures getter and setter are created in the same context, they also refer to the same context during theirs whole lifetime. Every call to closure_gen will incarnate a new context with three variables value, getter and setter! HTH, \cle