Dynamically creating class in Ruby

后端 未结 3 2070
后悔当初
后悔当初 2020-12-29 12:43

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         


        
3条回答
  •  粉色の甜心
    2020-12-29 13:15

    Assuming you want to create different classes per type/array size at runtime:

    If (like in Python) a Ruby class is defined when executed (I think it is), then you can do this:

    Define your class inside a function. Have the function recieve array size and type as parameters and return the class in its result. That way, you have a sort of class factory to call for each definition in your spec file :)

    If on the other hand you want to just initialize @params based on actual data, keep in mind, that Ruby is a dynamically typed language: Just reassign @params in your constructor to the new array!

提交回复
热议问题