Jonthemanman Jonthemanman - 5 months ago 10
Ruby Question

Dynamically creating objects in Ruby

I have a class whose

initialize
method defines a few instance variables and does some calculations. I need to create about 60 objects of that class. Each object has an ID number at the end. E.g.:

object1 = Dynamic.new(x, y)
object2 = Dynamic.new(x, y)
object3 = Dynamic.new(x, y)
...


I could just define them all by hand, but that would be quite inefficient. Is there any way to dynamically create each object?

Answer

You can always make a loop and push all the objects into an array. An array position might also be needed for knowing which object is each. This isn't quite what you wanted (atleast I don't think so), but it should suffice.

class Dynamic
@@instances_of_class = 0
  def initialize(x,y)
  #...
  @array_position = @@instances_of_class
  @@instances_of_class += 1
  end
end

ary = []
50.times do 
ary << Dynamic.new(x,y)
end

Edit: This solution, as said in the comments, can cause bugs if you change the array, so here's an alternate solution.

requier 'File.rb'
i = 1
varFile = File.open("File.rb","a+")
50.times do
varFile.puts "variable#{i} = Object.new"
i += 1
end

Inside of File.rb will be 50 uniquely named variables that you can use.

Comments