From: Brian Candler Date: 2007-03-01T23:11:43+09:00 Subject: Re: Newbie Question On Thu, Mar 01, 2007 at 10:22:39PM +0900, Brian Candler wrote: > > class Song < ActiveRecord::Base > > @@dcounts = [] > > > > def Song.count(difficulty, artistid) > > @@dcounts[difficulty][artistid] > > end > > > > def Song.count=(difficulty, artistid, val) > > @@dcounts[difficulty] ||= {} > > @@dcounts[difficulty][artistid] = val > > end > > end ... > However I wonder if perhaps you're going about this the wrong way. You're > using a class variable, @@dcounts, which implies that you plan to create > multiple instances of class 'Song'. So maybe what you really need is an > accessor on the individual Song object to set its difficulty, which could > also update your @@dcounts index for you. Are you trying to count, for each artist, the number of songs of a particular difficulty level? Then you can make the the difficulty an attribute of the song: class Song @@dcounts = [] def initialize(artistid, name, diff=nil) @artistid = artistid @name = name self.difficulty=(diff) end def difficulty=(diff) # decrement count at old difficulty (if any) if @difficulty @@dcounts[@difficulty][@artistid] -= 1 end # increment count at new difficulty if diff @@dcounts[diff] ||= {} @@dcounts[diff][@artistid] += 1 end # remember difficulty @difficulty = diff end end However if you are doing this with ActiveRecord, i.e. you have a SQL database on the backend, then I'd forget the class variable and let the database do the work for you. Store the difficulty as an attribute of the song, then you just need something like (untested) def Song.count(difficulty, artistid) Song.count_by_sql([ "SELECT COUNT(*) FROM songs WHERE id=? AND difficulty=?", artistid, difficulty]) end Or using :group conditions you could get all the songs grouped by difficulty and artistid, effectively populating your @@dcounts variable in one go. I'm I'm not sure if AR provides a method which will accept the output from a SELECT foo,COUNT(*) GROUP BY foo, but at worst you can send it directly to the underlying database. HTH, Brian.