新手问题 attr_accessor 定义的类变量如何在实例方法中访问???

xautjzd · May 29, 2013 · Last by reyesyang replied at May 29, 2013 · 2367 hits
class Test
   class << self
      attr_accessor :count
   end
   def add
      count += 1
       puts count
    end
end
test = Test.new
Test.count =5
puts Test.count
test.add

这样用 attr_accessor 定义了类变量,但是没法通过 add 实例方法来访问。请求指点

这种问题该收费。。

补下基础知识吧

#2 楼 @mojidong 就是看的基础知识呢

楼上的大神们要收费... 偷偷的说...self.class...

  • 这种方法其实并没有正真的创建类变量 @@count,而只是创建了一个 Test 这个 Class 实例的 实例变量 @count 和两个操作该变量的 singleton method
[9] pry(main)> Test.count = 1
=> 1
[10] pry(main)> Test.class_variables
=> []    #可以看出并没有创建真正的类变量 @@count
[11] pry(main)> Test.instance_variables
=> [:@count]    #作为 Class 实例的 Test,拥有了实例变量 @count
[13] pry(main)> Test.instance_methods(false)
=> [:add]
[15] pry(main)> Test.singleton_methods(false)
=> [:count, :count=]
You need to Sign in before reply, if you don't have an account, please Sign up first.