From: Jeff Coleman Date: 2006-04-08T15:18:00+09:00 Subject: Re: Simple Question About Deleting Instances 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. The Pickaxe book gives a good example of the difference between instance variables and class variables and how they can be useful. Perhaps this is stuff you already know, but it can be helpful to cover it again. In the Pickaxe example (paraphrasing the code), they're making a Jukebox application which plays songs and records the total number of plays of each song, as well as the total number of songs played by the jukebox. class Song attr_accessor :name, :artist, :duration, :plays @@total_plays = 0 # class variable, the total number of all songs played by the jukebox def initialize(name, duration) self.name = name # using the accessor methods self.artist = artist # using the accessor methods self.duration = duration # using the accessor methods plays = 0 # using the accessor methods end def play @@total_plays += 1 # increase the total count self.plays += 1 # increase the count for this song # play the song end end So if you do this: so_what = Song.new("So What", "Miles Davis", 9.24) so_what.play so_what.play Song.total_plays #=> 2 so_what.plays #=> 2 penny_lane = Song.new("Penny Lane", "The Beatles", 3.45) penny_lane.play penny_lane.play Song.total_plays #=> 4 penny_lane.plays #=> 2 So the "@@total_plays" variable stores a value unique to the class of Song, regardless of instances. And the instance variables store values unique to each instance. The class variable can be "declared" or used in the body of the class definition, but the instance variable should be used in the body of a method. I'm sure you know most of this, but hopefully it helps a bit. Jeff Coleman -- Posted via http://www.ruby-forum.com/.