0

im trying to optimize my code as much as possible and i've reached a dead end.

my code looks like this:

class Person
  attr_accessor :age
  def initialize(age)
    @age = age
  end
end

people = [Person.new(10), Person.new(20), Person.new(30)]

newperson1 = [Person.new(10)]
newperson2 = [Person.new(20)]
newperson3 = [Person.new(30)]

Is there a way where i can get ruby to automatically pull data out from the people array and name them as following newperson1 and so on..

Best regards

4
  • Why would you want to? Just use them from the array. Or create a hash with keys of "newperson" + an index. Commented Oct 7, 2013 at 19:17
  • Im quite new to ruby and as i said trying to optimize my code. can u make a example of using an hash for this example Commented Oct 7, 2013 at 19:20
  • If you have a collection of things, the optimal way to use it is as a collection, rather than pulling out separate variables. That's very unlikely to be an optimization. If what you want is to be able to have an identifier for each item, then a hash may be a good approach. For how to do it, look at sawa's example, but instead of setting a local variable using binding, first create a hash myhash = {} and then just do myhash["newperson#{1}"] = person. Commented Oct 7, 2013 at 19:25
  • 1
    in your code above you've actually created 6 Person objects and 4 arrays, just FYI. Commented Oct 7, 2013 at 19:32

2 Answers 2

0

That is definitely a code smell. You should refer to them as [people[0]], [people[1]], ... .

But if you insist on doing so, and if you can wait until December 25 (Ruby 2.1), then you can do:

people.each.with_index(1) do |person, i|
  binding.local_variable_set("newperson#{i}", [person])
end
Sign up to request clarification or add additional context in comments.

Comments

-1

I think this is what you're trying to do...

newperson1 = people[0]
puts newperson1.age

The output of this 10 as expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.