Reputation: 301
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?
Upvotes: 3
Views: 2594
Reputation: 46
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.
require '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.
Upvotes: 3
Reputation: 939
I would be curious to know why you need this. It's an unusual requirement, and often that means that you can avoid the problem instead of solving it. I think TheLuigi's solution would work, but if you use a class variable then these Id's will be shared across multiple classes. You can instead use an instance variable, with something like the following:
class A
def self.next_id
@id ||= 0 ; @id += 1
end
def initialize
@id = A.next_id
end
end
A.new
# => #<A:0x007fd6d414c640 @id=1>
A.new
# => #<A:0x007fd6d41454a8 @id=2>
Upvotes: 1
Reputation: 168101
If you just want sixty objects accessible from a variable, you should have them in an array referred to by a single variable.
objects = Array.new(60){Dynamic.new(x, y)}
Your object1
, object2
, ... will correspond to objects[0]
, objects[1]
, ... respectively.
Upvotes: -1