wannes <oeaniz / gmail.com> writes:

> def mfoo ... end creates a new scope (or how would you say
> that in proper naming),

You'd say it doesn't create closures.

> and thus forgets about local variables defined elsewhere,
> you can't access foo from within the method.
>
> I think you have 2 options here (maybe more, but these are
> the ones I can come up with as a newbie myself):
>
> 1) pass foo as an argument.
>   def mfoo(foo) ... end
>   mfoo(foo)
>
> 2) make foo an instance-variable
>   @foo = [..]
>   def mfoo
>      @foo.each...
>   end

You can also define the method as a closure:

   class Module
     public :define_method
   end

   moomin = 123                        # local variable
   def foo ; moomin end                # no closure
   (class << self ; self end).
     define_method(:bar) { moomin }    # closure

   foo # NameError: undefined local variable or method `moomin'
   bar #=> 123

But this is not a very practical or useful thing to do.
Usually, you would be working in some class of your own,
in which case you would simply use an instance variable.

-- 
Daniel Brockman <daniel / brockman.se>

    So really, we all have to ask ourselves:
    Am I waiting for RMS to do this?   --TTN.