当类动态变化时,如何实例化Ruby类的实例?

当类动态变化时,如何实例化Ruby类的实例?,ruby,Ruby,因此,我尝试用ruby创建一个文本游戏,并尝试创建一个fight方法来处理创建任何对象的问题。我在另一个文件中有一个Monsters类,还有一些子类,比如Rogue和Vampire。我通过使用一个case语句来实现这一点,该语句实例化了名为m的对象,该对象要么是流氓,要么是吸血鬼,并将几乎所有的方法放在怪物类中,以便它们共享相同的方法名称,但是有没有更有效的方法来处理未知对象呢 我的代码: def fight(monsterToFight) case monsterToFight when "

因此,我尝试用ruby创建一个文本游戏,并尝试创建一个
fight
方法来处理创建任何对象的问题。我在另一个文件中有一个
Monsters
类,还有一些子类,比如
Rogue
Vampire
。我通过使用一个
case
语句来实现这一点,该语句实例化了名为
m
的对象,该对象要么是
流氓
,要么是
吸血鬼
,并将几乎所有的方法放在
怪物
类中,以便它们共享相同的方法名称,但是有没有更有效的方法来处理未知对象呢

我的代码:

def fight(monsterToFight) 
case monsterToFight
when "Rogue"
  m = ::Rogue.new
when "Vampire"
  m = ::Vampire.new
else
  puts "error 503"
end
... #more code
链接到完整回购:

您可以使用

你可以用

class_name = "Rogue"

rogue_class = Object.const_get(class_name) # => Rogue

my_rogue = rogue_class.new # => #<Rogue ...>
def fight(name_of_monster_to_fight)
  monster_class = Object.const_get(name_of_monster_to_fight)
  m = monster_class.new

  # ... more code

rescue NameError # This is the error thrown when the class doesn't exist
  puts "error 503"
end