I have a class that should look something like this:
class Family_Type1 @people = Array.new(3) @people[0] = Policeman.new('Peter', 0) @people[1] = Accountant.new('Paul', 0) @people[2] = Policeman.new('Mary', 0) def initialize(*ages) for i in 0 ... @people.length @people[i].age = ages[i] end end end
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?
First off, part of the reason your example code isn’t working for you is that you have two different
@peoplevariables – one is an instance variable and the other is a class instance variable.If you want to create variables one time in a class to use in instance methods of that class, use
constantsorclass variables.Even so, in the context of your code, you probably don’t want all your instances of Family_Type1 to refer to the same Policemen and Accountants right? Or do you?
If we switch to using class variables:
The runtime initialization can be done with metaprogramming, as Chirantan said, but if you are only initializing a few classes, and you know what their name is, you can also do it just by using whatever you read from the file: