From: "David A. Black" Date: 2008-03-21T10:49:38+09:00 Subject: Re: including instance methods and setting an instance variable Hi -- On Fri, 21 Mar 2008, Leon Bogaert wrote: > Hi all, > > I'm trying to include a module and in that module I want to set an > instance variable. I have the following: > > class Queue > include LBo::InstanceMethods > end > > module LBo > module InstanceMethods > attr_accessor :position > self.position = 1 self at this point is the Module object LBo::InstanceMethods. You're calling the #position method on that Module object. > end > end > > q = Queue.new > q.position > > But I'm getting this error: > undefined method `position=' for LBo::InstanceMethods:Module > (NoMethodError) See above. > I'm feeling like a moron because I can't understand why this is not > working. > I tried setting the @position variable directly, but when I do > q.position it gives back nil. > > Could somebody lend me a hand with this one? It's mostly about 'self'. You have to be aware of what self is when you use it. Inside a module definition, it's the Module object itself. Inside an instance method, it's the instance. The job of the module is (mainly) to define instance methods that will be executed by objects yet unborn. The module itself has no direct access to the instance variables of those objects. But it can define methods that do things with them. For example: module LBo module InstanceMethods attr_writer :position def position @position ||= 1 end end end class C include LBo::InstanceMethods end C.new.position # 1 Here, I'm writing an instance method #position, which when executed with a C instance as 'self' will set the appropriate instance variable if that variable isn't set already. 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!