Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating objects in Ruby

Tags:

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?

like image 886
Strictly No Lollygagging Avatar asked May 03 '26 20:05

Strictly No Lollygagging


1 Answers

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.

like image 186
TheLuigi Avatar answered May 07 '26 11:05

TheLuigi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!