1

我有以下代碼:動態創建類

module City 
    class Bus < Base 
    end 

    class BusOne < Bus; end 
    class BusTwo < Bus; end 
    class BusSixty < Bus; end 
    .... 
end 

我的目標是動態創建這個類:

class BusOne < Bus; end 
    class BusTwo < Bus; end 
    class BusSixty < Bus; end 
    ... 

這就是爲什麼我想:

module City 
    class Bus < Base 
    DIVISON = [:one, :two, :sixty] 
    end 

    .... 
    Bus::DIVISONS.each do |division| 
    class "Bus#{division.capitalize}".constantize < Bus; end 
    end 
end 

但我得到這個錯誤:

unexpected '<', expecting &. or :: or '[' or '.' (SyntaxError) 

什麼我錯了嗎? 感謝

+0

我認爲你的答案值得綠黨。我的只是一個變種。 –

回答

0

這是約翰的回答的一個變種,主要是爲了展示使用send不是必需的。

module City 
    class Bus 
    def i_am 
     puts "this is class #{self.class}" 
    end 
    end 
end 

["BusOne", "BusTwo", "BusSixty"].each do |class_name| 
    City.const_set(class_name, Class.new(City::Bus)) 
end 

City::BusOne.new.i_am 
this is class City::BusOne 

City::BusTwo.new.i_am 
this is class City::BusTwo 

City::BusSixty.new.i_am 
this is class City::BusSixty 
1

作品有:

City.send(:const_set, "Bus#{division.capitalize}", Class.new(Bus))