jamal
1
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
jamal
2
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
3
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?
jamal
4
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
jamal
6
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
jamal
7
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