How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?
I’m looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.
You can use attribute accessors:
Now you can access it via:
Note that you can also use
attr_readerorattr_writerto define just getters or setters or you can define them manually as such:You can also use singleton methods if you just want it defined on a single instance:
FYI, in response to the comment on this answer, the singleton method works fine, and the following is proof:
As you can see, the singleton method
setitwill set the same field,@b, as the one defined using the attr_accessor… so a singleton method is a perfectly valid approach to this question.