Ruby 如何动态去调用类?

colorfulberry · 2015年06月16日 · 最后由 colorfulberry 回复于 2015年06月16日 · 1812 次阅读
module A
   class  B
      class Base
      end
   end
end

module A
   class B
      class C < A::B::Base
        def hello_c
          puts 'hello class C method hello_c'
        end
      end
   end
end

module A
   class B
      class D < A::B::Base
        def hello_d
          puts 'hello class D method hello_d'
        end
      end
   end
end

module A
   class B
      classs E < A::B::Base
        def hello_e
          puts 'hello class E method hello_e'
        end
      end
   end
end

................

str = ['c','d','e'].sample A::B.const_get(str.to_s.classify).new 这个是工作的 我想要实现 A::B.new(str) 来替代上面的方法,请问该怎么处理呢?@lgn21st @rei

module A
  class B
    def self.new(str)
      const_get(str.to_s.classify).new
    end
  end
end

@rei awesome,非常感谢!我刚开始用 initalize 死活不行, ☺ :plus1: 现在 get 到了http://stackoverflow.com/questions/24130457/the-difference-between-initialize-and-self-new

需要 登录 后方可回复, 如果你还没有账号请 注册新账号