我正在尝试在initialize中执行一个instance_eval,后跟一个attr_accessor,我不断得到:“initialize’:undefined方法’attr_accessor“.为什么这不工作?
代码看起来像这样:
class MyClass def initialize(*args) instance_eval "attr_accessor :#{sym}" end end
解决方法
您不能在实例上调用attr_accessor,因为attr_accessor未被定义为MyClass的实例方法.它只适用于模块和类.我怀疑你想在实例的Metaclass上调用attr_accessor,如下所示:
class MyClass def initialize(varname) class <<self self end.class_eval do attr_accessor varname end end end o1 = MyClass.new(:foo) o2 = MyClass.new(:bar) o1.foo = "foo" # works o2.bar = "bar" # works o2.foo = "baz" # does not work