Jonthemanman Jonthemanman - 8 months ago 24
Ruby Question

Dynamically creating objects in Ruby

I have a class whose

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 =, y)
object2 =, y)
object3 =, y)

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


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

ary = []
50.times do 
ary <<,y)

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.rb","a+")
50.times do
varFile.puts "variable#{i} ="
i += 1

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