From: Sean O'Dell Date: 2003-07-18T02:37:57+09:00 Subject: Re: What's the point? "Jim Freeze" wrote in message news:20030717103702.A3418@freeze.org... > Hi > > I've known for some time that methods can be defined inside > methods, but I am still wondering what's the point. > > def fred > def x > puts "x" > end > x > end > > fred > x > > produces > x > x > > Why would any sane person do such a thing? :) They're known as "local functions" I think (not sure if that is a universal term for them). I use these from time to time in Pascal. I have several uses for them: 1) To "tuck away" code in a function which makes the function hard to follow. For example, if a "for" statement has 15 lines of code in it (making code before and after the for statement spread apart), I might put all that code up into a local function and the for statement will just call it. The code itself isn't particularly re-usable, so I leave it out of the parent function's namespace and keep it in a local function. 2) Same as #1, but especially when I call the same code from more than one place in a function, and it's, again, not particularly re-usable. If the code ever hints at re-usability, then I find it a real home in a namespace somewhere. 3) To override other functions temporarily (perhaps even permanently). This is a bit like Aspect programming, I think. For example, if a function I've written calls printf, but for a test I want all the data being printed to go to both a file for logging purposes and to a TCP/IP connection for remote logging, I could write a local function called printf. Being able to re-define a function on-the-fly for quick debugging purposes is very nice. I like the fact that Ruby has local functions. It's mainly a procedural programming device, but personally, while I love Ruby's pure-OOP-ness, I think it's wise to also incorporate other programming idioms. Sean O'Dell