How do I set an attr_accessor for a dynamic instance variable?
this answer doesn't pollutes the class space, example.. if i do mine.my_number 4
then the other instances of Mine
will not get the my_4
method.. this happens because we use the singleton class of the object instead of the class.
class Mine def my_number num singleton_class.class_eval { attr_accessor "my_#{num}" } send("my_#{num}=", num) endenda = Mine.newb = Mine.newa.my_number 10 #=> 10a.my_10 #=> 10b.my_10 #=> NoMethodError
This can be accomplished using __send__
. Here:
class Mine attr_accessor :some_var def intialize @some_var = true end def my_number num self.class.__send__(:attr_accessor, "my_#{num}") self.__send__("my_#{num}=", num) endenddude = Mine.newdude.my_number 1puts dude.my_1=> 1
Easy. You can dynamically define the attribute reader inside the my_number method:
def my_number num self.instance_variable_set "@my_#{num}", num self.class.class_eval do define_method("my_#{num}") { num } end end
see if that works for you