On 4/22/06, dblack / wobblini.net <dblack / wobblini.net> wrote:
>
> To be fair to Sean, though, the question really had to do with
> clarifying how the scope of class_eval worked -- so removing it kind
> of defeats that particular purpose :-)
>
>
> David
>
Thanks for leaping to my defence David but I think James is right.

Anyway, back to Pat's question. I'll try to be more explicit in future.

The main difference between

  var = "initialized variable"
  class C;end
  C.class_eval { define_method(:test) { puts var} }

and

  var = "initialized variable"
  class D
    define_method(:test) { puts var } # will fail
  end

is that the closure passed to define_method in D is
within a new scope, i.e. the class definition, which means
it does not have access to the local variables in the outer scope, i.e. var.

You can access variables local to the class definition like this:

  class D
    var = "initialized variable"
    define_method(:test) { puts var } # will work
  end

which is quite interesting in its own right.

But if you want access to the outer scope, then use the first method.
Now you know why the code on page 350 of the RoR book was written that way!

Regards,

Sean