Forum: Ruby diff't way to create an instance

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5bc4f8ca6e5981c5fc5402c43b663953?d=identicon&s=25 Sylvester the Cat (Guest)
on 2005-11-22 04:10
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!
992fe8c19bbbc27f2b562a9f96efc03d?d=identicon&s=25 jamis (Guest)
on 2005-11-22 04:41
(Received via mailing list)
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
This topic is locked and can not be replied to.