实例变量第一次在哪里初始化为零?我可以将所有实例的默认值重新定义为其他值吗?
例如:
class Class
#some code here or maybe in an Object class
end
class Foo1
attr_accessor :bar
end
class Foo2
attr_accessor :bar
end
p Foo1.new.bar # result is not nil
p Foo2.new.bar # result is not nil
这可以通过修改阅读器来完成:
class Class
def attr_accessor(attr_name)
...
define_method "#{attr_name}" do
if instance_variable_get "@#{attr_name}_history"
instance_variable_get "@#{attr_name}_history"
else
"Not nil"
end
end
...
end
end
但这无助于理解 Ruby 的核心。非常感谢!