Ruby class variable, class attribute(class instance variable), class constant tips
class Class_Attribute
@var = 1 #class attribute or class instance variable
def initialize
@var = 2 #instance attribute
end
def report
@var # instance attribute, not the class attribute
end
def Class_Attribute.report
@var # class attribute
end
end
class Child_A < Class_Attribute
@var = 3
end
puts Class_Attribute.report #=> 1
puts Class_Attribute.new.report #=> 2
puts Child_A.report #=> 3
puts Child_A.new.report #=> 2
class Class_Constant
VAR = [ 'a' ]
VAR2 = [ 'b' ]
def self.report
VAR2[0]
end
end
class Child_C < Class_Constant
VAR2 = [ 'c' ]
end
puts Class_Constant::VAR[0] #=> 'a'
puts Class_Constant::VAR2[0] #=> 'b'
puts Class_Constant.report #=> 'b'
puts Child_C::VAR2[0] #=> 'c'
puts Child_C.report #=> 'b'
puts Child_C::VAR[0] #=> 'a'
from David A. Black:
@@avar = 1
class A
@@avar = "hello"
end
puts @@avar # => hello
A.class_eval { puts @@avar } # => hello
If you’re just looking to store some data in a variable which is unique to your class, but accessible from instances or externally, why not just use instance variables?
class A
@foo = "bar"
class << self; attr_reader :foo; end
end
nil
A.foo #=> "bar"
references:http://www.oreillynet.com/ruby/blog/2007/01/nubygems_dont_use_class_variab_1.html
No comments :
Post a Comment