From: Jacob Basham Date: 2007-11-07T16:07:54+09:00 Subject: Re: instantiate random subclasses of Creature (Dragon, TeethDeer, etc) Just the other week I taught myself how to make a plugin type architecture using a similar manner, their might be a better way to do this, but this works and it's simple. Wrap all of the plugin (creatures in your case) in the same namespace, and put them in their own directory. i.e. module Namespace module Creatures class Dragon def initialize() puts "Dragon#initialize" end end end end Then you may dynamically import the creatures into your program, and make an array of them in a snap. Dir['creatures/*.rb'].each { |path| require path } creatures = Namespace::Creatures.constants This gives you an array of Strings containing the names of all classes in the Namespace::Creatures namespace in the creatures directory. You can then initialize any of your creature objects using it's name in the Array. creature = Namespace::Creatures.const_get(creatures[0]).new # Dragon#initialize Now just add the random factor you desire someCreature = Namespace::Creature.const_get(creatures[rand(creatures.size)]) Have fun! Jake On Nov 6, 2007, at 10:44 PM, Thufir wrote: > I want to not just create Dragons, but randomly other creatures. > Perhaps from a hard coded list? I was thinking of using random > numbers and case statements, but surely there's ruby-esque way to > specify: > > types of creatures: > > AssistantViceTentacleAndOmbudsman.rb > Dragon.rb > IntrepidDecomposedCyclist.rb > TeethDeer.rb > > and then (pseudo-) randomly select one to instantiate? Symbols seem > promising but I'm not sure how to implement it. > > C:\code> > C:\code> > C:\code>type Driver.rb > require 'ArrayOfCreatures' > require 'Dragon' > require 'Creature' > > #numOfCreatures=Kernel.rand(3) > > puts "\nquantity of creatures:" > numOfCreatures = gets.chomp.to_i > > > someCreatures = ArrayOfCreatures.new #need to ensure that this array > can only hold Creatures > > > 0.upto(numOfCreatures) do |i| > someCreatures[i]=Dragon.new #all dragons? what about > TeethDeer's? > print "\n" > print "someCreatures[" > print i > print "]:\n" > print someCreatures[i].toString > end > > > C:\code> > > > > thanks, > > Thufir > >