Ruby Class Variables

0 views
Skip to first unread message

Jamal Soueidan

unread,
Apr 2, 2007, 9:50:15 AM4/2/07
to rubyonra...@googlegroups.com
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

--
Posted via http://www.ruby-forum.com/.

Jason Roelofs

unread,
Apr 2, 2007, 10:18:57 AM4/2/07
to rubyonra...@googlegroups.com
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

Jamal Soueidan

unread,
Apr 2, 2007, 10:46:42 AM4/2/07
to rubyonra...@googlegroups.com
Jason Roelofs 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?

Jason Roelofs

unread,
Apr 2, 2007, 10:56:18 AM4/2/07
to rubyonra...@googlegroups.com
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

On 4/2/07, Jamal Soueidan <rails-mai...@andreas-s.net> wrote:

Jamal Soueidan

unread,
Apr 2, 2007, 11:00:35 AM4/2/07
to rubyonra...@googlegroups.com
Jason Roelofs 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 Roelofs :D

Jamal Soueidan

unread,
Apr 2, 2007, 11:03:11 AM4/2/07
to rubyonra...@googlegroups.com
Jason Roelofs 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

Jason Roelofs

unread,
Apr 2, 2007, 11:36:16 AM4/2/07
to rubyonra...@googlegroups.com
On 4/2/07, Jamal Soueidan <rails-mai...@andreas-s.net> wrote:


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
Reply all
Reply to author
Forward
0 new messages