Hi --

On Sat, 22 Mar 2008, mutahhir hayat wrote:

> On Sat, Mar 22, 2008 at 12:32 AM, David A. Black <dblack / rubypal.com> wrote:
>> Hi --
>>
>>
>>  On Sat, 22 Mar 2008, Christopher J. Bottaro wrote:
>>
>> > Hello.  I want to do this.
>> >
>> > instance = MyClass.new
>> > x = 1
>> > def instance.foo
>> >  puts x
>> > end
>> > undefined local variable or method `x' for #<MyClass:0x31ca8c4>
>> >
>> > How do get rid of that error?
>>
>>  You can use define_method, which takes a block and therefore can use
>>  the local variables in scope at the time it's called. You'd have to do
>>  something equivalent to the familiar:
>>
>>    class Object
>>      def singleton_class
>>        class << self
>>          self
>>        end
>>      end
>>    end
>>
>>  (Aside to Matz: can we *please* have that in 1.9/2.0? :-)
>>
>>  and then:
>>
>>    instance.singleton_class.class_eval {
>>      define_method("foo") { puts x }
>>    }
>>
>
> The problem is of scope. foo is a method belonging to the 'instance'
> variable. 'x' is defined in global scope, but since its not $x its not
> a global variable. When you start using x inside the method, the
> interpreter doesn't recognize a 'x' variable defined, hence the error.
> Either, define x inside MyClass, or mark x as a global variable using
> $x, which would make...
>
> ....
> $x = 1
> def instance.foo
>   puts $x
> end

I know that the problem is scope. That's why I suggested a way to
manipulate the scope :-)

I definitely would not (and deliberately did not) throw a global
variable at it. Also, defining x inside MyClass doesn't help, because
that's also a different local scope.


David

-- 
Upcoming Rails training from David A. Black and Ruby Power and Light:
   ADVANCING WITH RAILS, April 14-17 2008, New York City
   CORE RAILS, June 24-27 2008, London (Skills Matter)
See http://www.rubypal.com for details. Berlin dates coming soon!