Ruby Class Variables

Hello,

I’m little confused about class variables

class Polygon
attr_accessor :sides
@@sides = 10
end

p Polygon.new.sides

I get nil as return from sides??

but when I do this

class Polygon
@@sides = 10
def sides
@@sides
end
end

This work, but then I need to write all the accessors for every global
variable?

Regards,
Jamal

You want #cattr_accessor

attr_accessor gives you:

def var; @var; end
def var=(val); @var = val; end

while cattr_accessor gives you:

def self.var; @@var; end
def self.var=(val); @@var = val; end

Which also means that you will normally do Polygon.sides.

Jason

Jason R. wrote:

You want #cattr_accessor

attr_accessor gives you:

def var; @var; end
def var=(val); @var = val; end

while cattr_accessor gives you:

def self.var; @@var; end
def self.var=(val); @@var = val; end

Which also means that you will normally do Polygon.sides.

Jason

Well I don’t want to write the set and get, I tought with attr_accessor
they write it for you?

attr_accessor writes out set/get for instance variables.

cattr_accessor writes out set/get for class variables.

Use those, and you don’t have to write out your own set/get

Jason

Jason R. wrote:

attr_accessor writes out set/get for instance variables.

cattr_accessor writes out set/get for class variables.

Use those, and you don’t have to write out your own set/get

Jason

Thanks Jason R. :smiley:

Jason R. wrote:

attr_accessor writes out set/get for instance variables.

cattr_accessor writes out set/get for class variables.

Use those, and you don’t have to write out your own set/get

Jason

I actually just try it out, undefined method cattr_accesstor?

class Link

cattr_accessor :url, :response

def initialize(url)
@@url = URI::parse(url)
@@response = Net::HTTP.get(@@url)
end

end

link = Link.new(“http://www.google.com/”)
p link.response

On 4/2/07, Jamal S. [email protected] wrote:

end

link = Link.new(“http://www.google.com/”)
p link.response

Hmm, as you are posting to the Rails mailing list, I assumed the Rails
environment. You can include ActiveSupport for yourself to use these
methods.

require ‘rubygems’
require ‘active_support’

Jason