# Diff't way to create an instance

**URL:** <https://www.ruby-forum.com/t/difft-way-to-create-an-instance/48559>\
**Category:** Ruby\
**Created:** [November 22, 2005, 4:10am UTC](https://www.ruby-forum.com/t/difft-way-to-create-an-instance/48559 "2005-11-22T04:10:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sylvester\_the\_Cat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f05b48/32.png) [@Sylvester\_the\_Cat](https://www.ruby-forum.com/u/Sylvester_the_Cat)\
**Post date:** [November 22, 2005, 4:10am UTC](https://www.ruby-forum.com/t/difft-way-to-create-an-instance/48559/1 "2005-11-22T04:10:51Z")

</div>

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” ??

thanks!

---

<div class="post-metadata">

**Author:** ![Sylvester\_the\_Cat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f05b48/32.png) [@Sylvester\_the\_Cat](https://www.ruby-forum.com/u/Sylvester_the_Cat)\
**Post date:** [November 22, 2005, 4:41am UTC](https://www.ruby-forum.com/t/difft-way-to-create-an-instance/48559/2 "2005-11-22T04:41:24Z")

</div>

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

> create an instance of an apple (a = Apple.new) and put it in the  
> 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
