Organize my array ruby

2019-09-19 08:11发布

问题:

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

回答1:

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


回答2:

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

newperson1 = people[0]
puts newperson1.age

The output of this 10 as expected.