The below uses pseudo-random number generation to populate an array
with various monsters, all inherit from Creature. Can a list of
classes which inherit from Creature be generated automagically? There
must be a better technique to fill the array then the case
statement…
puts “\nquantity of creatures:”
numOfCreatures = gets.chomp.to_i
someCreatures = ArrayOfCreatures.new
0.upto(numOfCreatures) do |i|
creatureType = Kernel.rand(4)
case creatureType
when 0
someCreatures[i]=AssistantViceTentacleAndOmbudsman.new
when 1
someCreatures[i]=Dragon.new
when 2
someCreatures[i]=DwarvenAngel.new
when 3
someCreatures[i]=TeethDeer.new
end
The below uses pseudo-random number generation to populate an array
with various monsters, all inherit from Creature. Can a list of
classes which inherit from Creature be generated automagically?
Perhaps:
class Creature @creature_classes = []
hook to note when a class inherits
def self.inherited(klass) @creature_classes << klass
end
generate a random creature from among known subclasses
def self.random_creature @creature_classes[ rand(@creature_classes.length) ].new
end
end
The below uses pseudo-random number generation to populate an array
with various monsters, all inherit from Creature. Can a list of
classes which inherit from Creature be generated automagically? There
must be a better technique to fill the array then the case
statement…
cfp: ~> cat a.rb
class Creature
Children = []
def self.inherited other
super
ensure
Children << other
end
end
The below uses pseudo-random number generation to populate an array
with various monsters, all inherit from Creature. Can a list of
classes which inherit from Creature be generated automagically? There
must be a better technique to fill the array then the case
statement…
I usually do this when I want to also recursively track subclasses:
Assuming that ArrayOfCreatures.new works like Array.new this can be simplified
to:
creatures = ArrayOfCreatures.new(num_of_creatures) do |i|
creature_classes[rand(4)].new
end
It took me a few reads to appreciate, but I like that alot
creatures = ArrayOfCreatures.new
[…]
num_of_creatures.times do |i|
creatures[i] = creature_classes[rand(4)].new
end
Assuming that ArrayOfCreatures.new works like Array.new this can be
simplified
to:
creatures = ArrayOfCreatures.new(num_of_creatures) do |i|
creature_classes[rand(4)].new
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.