From: Justin Collins Date: 2010-01-16T06:28:45+09:00 Subject: Re: Nested Function Confusion Josh Cheek wrote: > Hi, couldn't find any explanation of nested functions (other than an > acknowledgment of their existence) in Programming Ruby or the Ruby > Programming Language, so thought I'd see what people here could tell me. > > I'm having a difficult time understanding what is going on in this example: > def test > def test2 > end > end > > RUBY_VERSION # => "1.8.6" > defined? test # => "method" > defined? test2 # => nil > > defined? test::test2 # => "method" > defined? test2 # => "method" > > defined? test # => "method" > methods.grep( /test/ ) # => ["test2"] > > The first time I check whether test2 is defined, it returns nil, the second > time it returns "method" > When I check if test is defined, it returns 'method' but when I type > methods.grep(/test/) it only finds "test2" > > > Also, when should nested functions/methods be used? > Are nested functions redefined upon each call to the outer function? > Are there scope restrictions that would make it sensible to use nested > functions to enforce encapsulation of interdependent logic? > > Thanks, > Josh > > Ruby doesn't support defining nested functions like this very well, so I would say they should never be used, if possible. Instead, use lambdas, procs, or other closure-like constructs. Try searching for "ruby nested methods" and you will find past discussions of this. Nested functions are not really nested, but are flattened into the same scope. Try running test2, then test1, then test2 again. Yes, nested functions will be redefined each time the def...end code is run. You can verify by having two different definitions in an if statement. Also, defined? is a strange and mystical beast that should probably be avoided. -Justin