I have an object created, and I want, based on some conditional check, to add some attributes to this object. How can I do this? To explain what I want:
A=O
If the name of the attribute is known at code-writing time then you can do what was suggested already:
class A
end
a = A.new
a.age = 20 # Raises undefined method `age='
# Inject attribute accessors into instance of A
class << a
attr_accessor :age
end
a.age = 20 # Succeeds
a.age # Returns 20
b = A.new
b.age # Raises undefined method, as expected, since we only modified one instance of A
However, if the attribute's name is dynamic and only known at runtime then you'll have to call attr_accessor
a bit differently:
attr_name = 'foo'
class A
end
a = A.new
a.foo = 20 # Raises undefined method `foo='
# Inject attribute accessors into instance of A
a.instance_eval { class << self; self end }.send(:attr_accessor, attr_name)
a.foo = 20 # Succeeds
a.foo # Returns 20