Hi --

On Sun, 9 Jul 2006, anne001 wrote:

> I can't find what the problem is with @foundinfo: since it is defined
> outside a block, the block should find it no? @item is defined outside
> the second block and that second block finds it. What is @item and
> @foundinfo different?
>
> Do I have a typo I don't see, or it there a principle of the thing?

There's a principle:

Whenever you see this:

    @var

you are seeing an instance variable that belongs to whatever object is
"self" at that moment in runtime.

Now, watch this:

   class C
     puts self
     def x
       puts self
     end
   end

   C.new.x

What you get from this code is:

   C
   #<C:0x325648>

In other words, in the top level of a class definition block, "self"
is the class object itself (C, in this case).  Inside a method
definition -- that is, when that method is eventually executed --
"self" is the instance that's executing the method: hence the
"instance of C" inspect string on the second line.

It follow that when you do this:

   class C
     @var = 1
     def x
       @var = 2
     end
   end

you're dealing with two separate, unrelated instance variables, owned
by different objects.


David

-- 
http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
http://www.manning.com/black     => RUBY FOR RAILS, the Ruby book for
                                                     Rails developers
http://dablog.rubypal.com        => D[avid ]A[. ]B[lack's][ Web]log
dblack / wobblini.net              => me