diff't way to create an instance

S

Sylvester the Cat

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!
 
J

Jamis Buck

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top