Bradley, Todd wrote:
> Hi, I'm just now getting into Ruby's OO-ness, and could use some advice.
> I'm trying to create an object, but which specific class needs to be
> determined at runtime.  I figured out how to do this by creating a
> string and executing it using the "eval" command, but I know there must
> be an easier way.  My first guess was to do something like #{answer}.new
> but that didn't work.
> 
> 
> Here's my code:
> 
> 
> class Foo
> 	def method1
> 	end
> end
> 
> class Bar
> 	def method2
> 	end
> end
> 
> # Pretend this was determined at runtime
> answer = "Foo"
> 
> 
> # There must be a better way of doing this:
> 
> myobj = Object.new # Needs to exist in this scope
> mystring = "myobj = #{answer}.new"
> 
> eval mystring
> 
> puts "I just created a #{myobj.class} object."
> 

You could do:

   myobj = eval("Foo.new")

or

   myobj = eval("Foo").new

or even

   myobj = Object.const_get( "Foo" ).new

I prefer the second option listed, since it is easier to pass arguments 
to constructor, and less verbose than the third option.

- Jamis

> 
> 
> 
> Any advice is appreciated.  Thanks in advance!
> 
> 
> Todd.
> 
> 
> 


-- 
Jamis Buck
jgb3 / email.byu.edu
http://www.jamisbuck.org/jamis