Ruby类级别附件的行为与类的内部和外部不同

时间:2014-06-01 07:17:25

标签: ruby metaprogramming metaclass

代码胜过千言万语:为什么这段代码会起作用?

class MyClass 
  @variable = 0

  class << self
    attr_accessor :variable 
  end

  puts variable # => 0, as expected
  variable = 1
  puts variable # => 1, as expected
  puts self.variable # added after @Arup's comments => 0
end

puts MyClass.variable # => 0, as really not expected!
MyClass.variable = 2
puts MyClass.variable # => 2, as expected

为了记录,我已经阅读了所有我能在元类上找到的东西和“阶级是一个对象”的理论,但这对我来说仍然没有意义。

variable = 1从类中设置了哪个变量,哪个变量是由MyClass.variable = 2设置的?为什么可以从类定义内部和外部访问该附件,但它有不同的作用吗?

或者只是非常简单:这里发生了什么?

0 个答案:

没有答案