[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Class Instantiation

jantzeno

8/14/2007 9:24:00 PM

I have a few questions about class instantiation.

Say I have a class:

class Person
attr_accessor :name, :age
end

And an array:

names = ["john", "jane"]

Is it possible to instantiate a class using a string from the array so
I get something equal to:

john = Person.new
jane = Person.new


v/r,


4 Answers

dougal.s

8/14/2007 9:33:00 PM

0

On 14 Aug 2007, at 22:24, jantzeno wrote:
>
> Is it possible to instantiate a class using a string from the array so

names.each do |n|
eval n + ' = Person.new'
end

I'm sure there is a neater solution to this, but I'll put this
forward for now.

Douglas F Shearer
dougal.s@gmail.com
http://douglasfs...



Todd Burch

8/14/2007 9:39:00 PM

0

jantzeno wrote:
> I have a few questions about class instantiation.
>
> Say I have a class:
>
> class Person
> attr_accessor :name, :age
> end
>
> And an array:
>
> names = ["john", "jane"]
>
> Is it possible to instantiate a class using a string from the array so
> I get something equal to:
>
> john = Person.new
> jane = Person.new
>
>
> v/r,

You can, but it might be better to do something like this if you have
lots of names in your names array:

people = Array.new ;

names.each_with_index {|n,i|
people[i] = Person.new ;
people[i].name = n ;
}

Todd
--
Posted via http://www.ruby-....

David A. Black

8/14/2007 9:41:00 PM

0

jantzeno

8/14/2007 10:07:00 PM

0


>
> The best and most common advice given in response to this question is:
> do it with a hash instead, like this:
>
> people = {}
> names.each {|name| people[name] = Person.new }
>

This was going to be my next question.

Then I can do a:

people["john"].name = "john"

Brilliant, thanks.