On Nov 21, 2005, at 8:10 PM, Sylvester the Cat wrote:

> Hello!
> I am new to Ruby and have a question that seems easy but I'm unsure
> where to look on the Net for a solution:
>
> Is there a way to create an instance of a class other than  
> using .new()
> method?
> Esp when I don't know the Class name at design time
>
> example:  I have a collection of objects like a shopping basket.  I
> create an instance of an apple (a = Apple.new) and put it in the  
> basket.
> I create a banana and do the same (B = Banana.new).
>
> Now you say to me "oh hey, we need Kiwi!" All I have from this message
> is the literal string "Kiwi" (message = "kiwi"). How do I create an
> instance of a Kiwi ??
>
> I can't do
> k = #{message}.new
> nor
> k = "#{message}.new"
> nor
> k = "Kiwi".new
>
> because that is literally the string object "Kiwi".
>
> Is there an alternate such as k = createObject("kiwi").new
> a related question: what is this sort of problem called?! "Creating an
> instance of a class by reference" ??

Class names are just constants that point to the class. You can get  
the constant using the #const_get method of Object:

   Object.const_get("Kiwi").new

Perhaps simpler, just use eval:

   eval("Kiwi").new

or

   eval("Kiwi.new")

- Jamis