On 3/1/07, Dick <rwk / americom.com> wrote:
> Hi,
>
> I am new to Ruby.  This is the very first class I am writing and it
> doesn't seem that Ruby is designed to handle what I thought should work.
> Why doesn't the below work?
>
> class Song < ActiveRecord::Base
>   @@dcounts = []
>
>   def Song.count(difficulty, artistid)
>     @@dcounts[difficulty][artistid]
>   end

You've already stimulated discussion on the restrictions on x= methods in Ruby.

Since you say this is your first ruby class, I feel the need to
critique the use of class variables.

While there might be some uses of class variables, I tend to see a
little red light go off every time I see @@ in ruby code.  It's not
likely that a class  variable will do what the programmer thinks it
does, since class variables are shared between classes and subclasses.
 In most cases what you really want are class INSTANCE variables which
look just like instance variables except that they appear in the
context of a class method.

I'd rewrite that beginning code as something like

class Song < ActiveRecord::Base
      # This defines an accessor for the dcounts class instance variable
      # note that this is a class method
      # it could also have been defined as def self.dcounts, but I usually
      # prefer naming the class as a matter of style.
      def Song.dcounts
         # if @dcounts is  nil initialize it to an empty array
         # in any case return it.
         # This is a standard ruby idiom for lazy initialization
         @dcounts ||= []
       end

      # Another class method, I used the accessor so that
      # @dcounts will be properly intialized, other references should
      # do the same.
      def Song.count(difficulty, artistid)
          dcounts[difficulty][artistid]
     end
...

HTH

-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/