Jamis Buck wrote:
> Sorry if this has been rehashed before--I searched the archive and 
> didn't find anything that seemed identical to the question I've got.
> 
> Which is: if I define a method inside a method, currently the inner 
> method has no access to the outer method's local variables.  Is this a 
> conscious design decision, or a bug?
> 
>  def test_outer( a, b )
>     def test_inner( a )
>        puts "#{a} and #{b}"
>     end
> 
>     test_inner( a+b )
>  end
> 
>  test_outer( 1, 2 )
> 
> I would expect "3 and 2" to be the output, but I get an "undefined local 
> variable or method `b'" error from test_inner.
> 
> Can anyone shed some light on this behavior for me, either in favor of 
> it, or at the very least explaining it?  (Yes, I know I could use a 
> block, instead of a nested method... but I would like to know why the 
> nested method approach fails.)

I can't give much of an explanation of the rationale, but here's a way 
to do what you were probably trying to do:

  def test_outer( a, b )
     self.class.instance_eval do
       define_method :test_inner do
          puts "#{a} and #{b}"
       end
     end

     test_inner( a+b )
  end

  test_outer( 1, 2 ) # ==> prints "1 and 2"

The reason this works is that #define_method, unlike the def "special 
form", takes a closure. You have to do the "self.class.instance_eval" 
because #define_method is private.