代码之家  ›  专栏  ›  技术社区  ›  John Smith

动态创建类[重复]

  •  2
  • John Smith  · 技术社区  · 8 年前

    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)
    

    谢谢

    2 回复  |  直到 8 年前
        1
  •  1
  •   Cary Swoveland    8 年前

    这是约翰答案的变体,主要用于显示 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
    
        2
  •  1
  •   John Smith    8 年前

    适用于:

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