Class Instantiation

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,

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
[email protected]

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

Hi –

On Wed, 15 Aug 2007, Douglas F Shearer wrote:

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

That won’t work, both because it’s inside a block:

1.times do
david = 1
end

p david # error – undefined

and because eval creates its own binding for local variable
assignments:

eval(“a = 1”)
p a

For both reasons, the variable would already have to be in view before
the eval.

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 }

David

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.

hi its seems like you have done a hard work on it. I have got lots of

information from your post. Really appreciate your work.!! It was

describe very nicely keep us doing good work…
http://www.dealsourcedirect.com/ion-tape2pc.html