Ruby – Dynamically creating class in Ruby


I have a class that should look something like this:

class Family_Type1
    @people =
    @people[0] ='Peter', 0)
    @people[1] ='Paul', 0)
    @people[2] ='Mary', 0)

    def initialize(*ages)
        for i in 0 ... @people.length
            @people[i].age = ages[i]

I want to be able to define a bunch of classes similar to this one at runtime (define them once at startup) where the size of the array and the type assigned to each parameter is defined at runtime from an external specification file.

I sort of got it to work using evals but this is really ugly. Any better way?

Best Solution

From what I understand, you need meta-programming. Here is a snippet of code for creating classes dynamically (on the fly) with initialize method that initializes instance variables-

class_name = 'foo'.capitalize
klass = Object.const_set(class_name,

names = ['instance1', 'instance2'] # Array of instance vars

klass.class_eval do
  attr_accessor *names

  define_method(:initialize) do |*values|
    names.each_with_index do |name,i|
      instance_variable_set("@"+name, values[i])
  # more...

Hope you can tweak it to suit your requirements.