def my_number num self.class.__send__(:attr_accessor, "my_#{num}") self.__send__("my_#{num}=", num) end end
dude = Mine.new dude.my_number 1 puts dude.my_1
#=> 1
#or def my_number num self.instance_variable_set "@my_#{num}", num self.class.class_eval do define_method("my_#{num}") { num } end end #or class Mine # ... def my_number num class << self attr_accessor "my_#{num}" end self.send("my_#{num}=", num) end end
class Widget # class instance variable pattern class << self; attr_accessor :color; end
def show_color() "This widget is #{self.class.color}" end end class WidgetR < Widget @color = "Russet" end class WidgetC < Widget @color = "Cordovan" end class WidgetL < Widget @color = "Liver" end
WidgetR.new.show_color #=> "This widget is Russet" #or class A @count = 0 @@count = 0 def self.inherited(subclass) subclass.instance_eval { @count = 0 } end def self.num_instances @count end def self.num_subclass_instances @@count end def self.new @count += 1 @@count += 1 super end end class B < A end class C < B end