On 8/17/07, Larry Kluger <rubyforum / kluger.com> wrote:
>
> Hi,
>
> How can a method gain access to the enclosing method's locals?
>
> def go2(arg)
>   def hi
>     puts "Hi #{arg}!"
>   end
>
>   a={:h => :hi}
>   send(a[:h])
> end

def initialize
  @submeths = {}
end

def dispatch(name, *args)
   if @submeths.has_key? name
     @submeths[name].call(*args)
   else
     send(name, *args)
   end
end

def submeth(name, &block)
   @submeths[name] = block
end

def go2(arg)
   # hi = lambda { puts "Hi #{arg}!" }
   # personally I would skip the submeths ivar altogether and just do hi.call
  # but this is mildly more entertaining
  submeth(:hi) { puts "Hi #{arg}" }

  a={:h => :hi}
  dispatch(a[:h])
end


>
> go2 'Larry' ==>> NameError: undefined local variable or method `arg' for
> main:Object
>
> In go2, is there a clean way for the hi method to have access to the
> arg local?
>
> Thanks!
>
> Larry
> --
> Posted via http://www.ruby-forum.com/.
>
>