On 4/8/06, Jeff Coleman <progressions / gmail.com> wrote:> Nathan O. wrote:>> Austin Ziegler wrote:>>> No. To clarify my statement:>>>>>>   #attr_accessor creates a pair of instance methods that access and>>>   may instantiate an instance variable, but don't have to.>>>>>> Instance variables are always bound to a particular value of self.>>> (I'm not *quite* sure where class variables reside.)>>> ...>>> "class Foo", "class << self", and "def myself" all change scope and>>> the meaning of "self" in that scope.>> Way, way over my head, but that probably has something to do with the>> two-year-old demanding that I stop reading and start wrestling with>> him. I'll sleep on this one. Thanks! I think I might have a shot at>> understanding this one in the morning.> As traditional as they are, for me the Foo/bar style examples can be> confusing because they give no context.
Fair enough. However, let me point out that you showed something*different* than I showed. I deliberately didn't get into classvariables (@@var) because the point I was making was solely about thechange of scope, and @@var is a little funny with scope (I personallythink it's broken, and I simply don't use them any more).
In many ways, the Pickaxe Song/Jukebox example is bad anyway; the*Jukebox* should be keeping track of how many songs it has played, notthe Song class, which may be used by other Jukebox instances, and forbilling purposes, you don't want those song counts commingled. :)
In your example, you also didn't give a definition forSong::total_plays.
If, however, we were to accept the Pickaxe premise as valid, here's whatI would do:
  class Song    attr_accessor :name    attr_accessor :artist    attr_accessor :duration    attr_reader   :plays
    # Class instance variable    @total_plays = 0
    class << self      attr_reader :total_plays    end
    # This could be in the class << self as def add_play...    def self.add_play      @total_plays += 1    end
    def initialize(name, artist, duration)      self.name = name      self.artist = artist      self.duration = duration      @plays = 0    end
    def play      self.class.add_play      @plays += 1      # play the song    end  end
@total_plays in the "class Song" scope belongs to the self that *is*"class Song". This is the same scope within "def self.add_play" or inthe method defined by "class << self; attr_reader :total_plays; end".
-austin--Austin Ziegler * halostatue / gmail.com               * Alternate: austin / halostatue.ca