I'm trying to do an instance_eval
followed by a attr_accessor
inside initialize
, and I keep getting this: ``initialize': undefined method 'attr_accessor'`. Why isn't this working?
The code looks kind of like this:
class MyClass
def initialize(*args)
instance_eval "attr_accessor :#{sym}"
end
end
A cleaner implementation (NB: This will add the accessor to ALL instances of the class, not just the single instance, see comments below):
Rob d'Apice has it almost right. You just need to write:
or
or my favorite variant
assuming the value of
varname
is a symbolYou can't call attr_accessor on the instance, because attr_accessor is not defined as an instance method of MyClass. It's only available on modules and classes. I suspect you want to call attr_accessor on the instance's metaclass, like this: