Hi --

On Sat, 22 Mar 2008, Leon Bogaert wrote:

> This guy: http://www.ruby-forum.com/topic/142444
> had the same question as me. Reading that post made things a lot
> clearer.
>
> It's difficult to apprehend how this stuff works in Ruby. Especially if
> you read some stuff like instance_eval and the lot.

It's not that hard; it's all based on a small number of principles
that never change.

1. Some object is always "self"
2. Every instance variable belongs to "self"
3. obj.instance_eval {...} temporarily (for the duration of the code
block) sets self to obj.

The hardest one seems to be #2. But it makes sense once you realize
that there is *always* a "self". So when you see this:

   module M
     @x = 1
     def my_method
       @x = 1
     end
   end

you're seeing two "self" contexts: the outer level of the module
definition (where self is M) and the inside of the method definition
(where self is, or rather will be, whatever object calls my_method.
Therefore, the two "@x"s have nothing whatsoever to do with each
other.

I should add:

4. Classes and modules are objects

which is, as I'm fond of saying to my trainees, the answer to about
75% of all questions about Ruby :-)

You also have to keep in mind that self is not the same as local
scope. self changes, and local scope changes, but not always in sync
with each other. They're two different things.


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!