我正在尝试创建一个自定义 attr_accessor,但似乎无法使其正常工作。它不是返回分配给编写器的值,而是返回实例变量。有任何想法吗?
class Object
def custom_attr_accessor(klass, attribute)
ivar = "@#{attribute}".to_sym
writer_body = lambda { |arg| instance_variable_set(ivar, arg) }
reader_body = lambda { ivar }
klass.send(:define_method, "#{attribute}=".to_sym, &writer_body)
klass.send(:define_method, "#{attribute}".to_sym, &reader_body)
end
end
class Person
end
custom_attr_accessor(Person, :age)
me = Person.new
me.age = 100
puts me.age
=> @年龄