Class Instantiation

J

jantzeno

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,
 
T

Todd Burch

jantzeno said:
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 = Person.new ;
people.name = n ;
}

Todd
 
D

dblack

Hi --

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

--
* Books:
RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
& consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
 
J

jantzeno

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.
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top