2015-12-16 133 views
1

所以我試圖創建一個紅寶石文本遊戲,並且我試圖創建一個可以處理創建任何對象的方法fight。我在另一個文件中有Monsters類,子類如RogueVampire。我設法通過使用case語句實例化一個名爲m的對象,該對象是RogueVampire,並將Monsters類中的幾乎所有方法都放在一起,以便它們共享相同的方法名稱,但效率更高處理未知對象的方式?如何在類動態更改時實例化一個Ruby類的實例?

我的代碼:

def fight(monsterToFight) 
case monsterToFight 
when "Rogue" 
    m = ::Rogue.new 
when "Vampire" 
    m = ::Vampire.new 
else 
    puts "error 503" 
end 
... #more code 

鏈接到全回購:https://github.com/chaseWilliams/textGame

回答

0

您可以使用const_get

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