There's one problem with the two methods here... if an instance variable is set in one instance, its accessor will be available to all instances, because you're defining methods on self.class
instead of on self.
dude = Mine.new
dude.my_number 1
puts dude.my_1
dudette = Mine.new
dudette.my_1 = 2 # works, but probably shouldn't
dudette.my_number 2
dude.my_2 = 3 # works, but probably shouldn't
What you probably want to do is modify only the instance that has the instance variable:
class Mine
# ...
def my_number num
class << self
attr_accessor "my_#{num}"
end
self.send("my_#{num}=", num)
end
end
This way, instance variables only get accessors on the objects they were created for. I also didn't bother with instance_variable_set, because if you're setting an accessor, then I think it reads better to just reuse that. But that's a style call. The big deal here is calling class << self
instead of self.class
.