Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Getting Class Variables in class method
Index -> Programming, Ruby -> Ruby Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
DtY




PostPosted: 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?
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: 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>]
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
DtY




PostPosted: 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 @@)
Tony




PostPosted: 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...
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
wtd




PostPosted: Tue Jul 14, 2009 12:31 pm   Post subject: RE:Getting Class Variables in class method

Classes are objects.
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: