From: Joel VanderWerf Date: 2003-03-21T13:48:46+09:00 Subject: Re: Strong advantages over Python Paul Prescod wrote: > Greg McIntyre wrote: ... >> In Python you can assign function names to variables and then call them >> through those variables, however AFAIK this relies on separate function >> definitions and global variables in order to achieve the same level of >> context manipulation possible with a Ruby block, so it certainly isn't >> as clean and easy. > > > I'm having trouble following this bit. It's true that you can't directly > overwrite a variable in a surrounding context. I don't know that this > has anything to do with assigning function names to variables or global > variables or anything. The usual workaround is to mutate an object > rather than overwriting a variable. > > def a(): > state = {} > def putin(x): > state["something"] = x > def getout(x): > return state["something"] > return putin, getout > > But every example I see of this seems contrived to me. You're trying to > build a "thing" which has both mutable state and functional behaviour. > Well, in OO languages we tend to call those things objects. > > class a: > def putin(self, x): > self.something = x > def getout(self, x): > return self.something I used to argue that closures were just another way of encapsulating state and behavior, so a clean OO language would omit them (TOOWTDI). But I've been convinced that closures and objects are two tools that, used side by side, can really make code more elegant (The Ruby Way, IMO). Closures can be created on the fly and, since we're using ruby, we can use block syntax to do so. This is especially useful for GUI callbacks. A snippet using an imaginary GUI toolkit: icon = Icon.new(...) SliderControl.new("Horizontal position") do |new_x| icon.move_to(new_x, icon.y) end Could this be made so elegant in Python?