Hi --

On Sat, 22 Apr 2006, Pat Maddox wrote:

> On 4/22/06, Sean O'Halpin <sean.ohalpin / gmail.com> wrote:
>> On 4/22/06, Pat Maddox <pergesu / gmail.com> wrote:
>>
>>> Can someone explain to me what the difference is between the inline
>>> code example, and specifying it inside the class?
>>
>> A class definition introduces a new scope (similar to def) so for your
>> example to work you need to define the local variable ~within~ the
>> class definition for it to be visible from the closure, e.g.
>>
>>   class A
>>     var = "initialized variable"
>>     class_eval { define_method(:talk) { puts var } }
>>   end
>>
>>   A.new.talk
>>
>>   #=> initialized variable
>>
>> Regards,
>>
>> Sean
>>
>>
>
> The point of this is to be able to access 'var' even though it's
> normally outside of the class's scope.  See the very first example,
> which does this.

But look closely at it:

irb(main):001:0> var = "initialized variable"
=> "initialized variable"
irb(main):002:0> class C; end
=> nil
irb(main):003:0> C.class_eval { define_method("talk") { puts var } }
=> #<Proc:0x00355c30@(irb):3>
irb(main):004:0> C.new.talk
initialized variable

The variable var is defined at the top level, and the call to
class_eval takes place at the top level.  So var is in scope, and can
be used inside the class_eval block.

In your example, var is on one side of a class keyword, and the use of
var is on the other.  What you've done is like:

   var = 1
   class C
     puts var
   end

which will give you the same error.


David

-- 
David A. Black (dblack / wobblini.net)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

"Ruby for Rails" PDF now on sale!  http://www.manning.com/black
Paper version coming in early May!