From: dblack@... Date: 2006-09-23T17:24:00+09:00 Subject: Re: How do I instantiate a class who's name is dynamic? Hi -- On Sat, 23 Sep 2006, Ben Harper wrote: > I want to do the following, where 'somefile' is a dynamic value: > require 'somefile.rb' > 'somefile.rb' will have a module inside it named "Magic_Module_somefile" > Inside that module there will be a class named "Magic_Class_somefile" > How do I new() that class ? You can get at it using const_get. Here's an irb demo: irb(main):001:0> s = "somefile" => "somefile" irb(main):002:0> module MM_somefile; class MC_somefile; end; end => nil irb(main):003:0> Object.const_get("MM_#{s}").const_get("MC_#{s}").new => # It's also possible to write a const_get variant that handles the :: separator automatically: class Object def const_get_recursive(const) const.split("::").inject(Object) {|c1,c2| c1.const_get(c2)} end end const_get_recursive("MM_#{s}::MC::#{s}").new David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org