# Nested Function Confusion

**URL:** <https://www.ruby-forum.com/t/nested-function-confusion/181678>\
**Category:** Ruby\
**Created:** [January 15, 2010, 9:55pm UTC](https://www.ruby-forum.com/t/nested-function-confusion/181678 "2010-01-15T21:55:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jcain](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3d9bf3/32.png) [@jcain](https://www.ruby-forum.com/u/jcain)\
**Post date:** [January 15, 2010, 9:55pm UTC](https://www.ruby-forum.com/t/nested-function-confusion/181678/1 "2010-01-15T21:55:32Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jcain](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3d9bf3/32.png) [@jcain](https://www.ruby-forum.com/u/jcain)\
**Post date:** [January 15, 2010, 10:34pm UTC](https://www.ruby-forum.com/t/nested-function-confusion/181678/2 "2010-01-15T22:34:10Z")

</div>

Josh C. wrote:

> RUBY\_VERSION # =\> “1.8.6”  
> time it returns “method”  
> 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
