Computer Science Canada

Getting Class Variables in class method

Author:  DtY [ Mon Jul 13, 2009 3:32 pm ]
Post subject:  Getting Class Variables in class method

I wrote a class that keeps track of all the instances created in the variable @@settings, now I need a class method to read it back.

so, I have:
Ruby:
def UserSettings.all
@@settings
end

Which tells me that the class variable @@settings doesn't exist. It must be trying to read Class' @@settings, since this is inside a singleton method for Class. I tried @settings, which gave me nil (doesn't exist, I assume). So is there a method or something I can use to read a class variable?

Author:  Tony [ Mon Jul 13, 2009 5:17 pm ]
Post subject:  Re: Getting Class Variables in class method

@var is the class variable
Ruby:

irb(main):001:0> class Foo
irb(main):002:1> @list = []
irb(main):003:1> def self.all
irb(main):004:2>   @list
irb(main):005:2> end
irb(main):006:1> def initialize
irb(main):007:2>   Foo.all << self
irb(main):008:2> end
irb(main):009:1> end
=> nil
irb(main):010:0> Foo.new
=> #<Foo:0x7d7f8>
irb(main):011:0> Foo.new
=> #<Foo:0x77aec>
irb(main):012:0> Foo.all
=> [#<Foo:0x7d7f8>, #<Foo:0x77aec>]

Author:  DtY [ Mon Jul 13, 2009 7:14 pm ]
Post subject:  RE:Getting Class Variables in class method

Okay, thanks. If you can do it like that, what is the use of class variables? (Like with @@)

Author:  Tony [ Tue Jul 14, 2009 9:11 am ]
Post subject:  RE:Getting Class Variables in class method

Wait, no... I've got things confused.

var -- local variable
@var -- instance variable
@@var -- class variable
$var -- global variable

The above _should_ be using @@class. I'm not entirely sure how it even works with the instance variable...

Author:  wtd [ Tue Jul 14, 2009 12:31 pm ]
Post subject:  RE:Getting Class Variables in class method

Classes are objects.


: