2014-05-02 35 views
0

我有一個「攻擊」的方法,由於某種原因,返回ArgumentError: wrong number of arguments (0 for 1),即使我提供一個參數。電話是a.attack(b)如果a和b是UnitInstance類引發ArgumentError:錯誤的參數數目(0 1),甚至提供的參數

的情況下,這是我的類和攻擊方式是在鈕 - 任何建議都非常感謝!

編輯:另外,這是一個Rails應用程序內的模型,但它並不需要連接與他DB

class UnitInstance 
    attr_accessor :name, :health, :current_health, :attack, :defence, 
    :initiative, :amount, :conditions 

    def initialize(unit_id, amount) 
     unit = Unit.find(unit_id) 
     @name = unit.name 
     @health = unit.health 
     @current_health = unit.health 
     @attack = unit.attack 
     @defence = unit.defence 
     @initiative = unit.initiative 
     @amount = amount 
     @conditions = [] 
    end 

    def strength 
     amount * attack 
    end 

    def dead? 
     health <= 0 and amount <= 0 
    end 

    def find_target(enemies) 

    end 

    def decrease_health(_amount) 
     hp = health * (self.amount - 1) + current_health 
     hp -= _amount 
     self.amount = hp/health + 1 
     if hp % health == 0   
      self.amount -= 1 
      self.current_health = 5 
     else 
      self.current_health = hp % health 
     end 
    end 

    def attack(target) 
     target.decrease_health(strength) 
     decrease_health(target.defence) unless target.dead?  
     "#{name.titleize} attacked #{target.name.titleize} for #{attack} damage," 
    end 

end 

回答

2

你有你的a.attack(b)

調用名爲 attack有一個參數的方法
def attack(target) 
    target.decrease_health(strength) ## <<-- Notice this 
    decrease_health(target.defence) unless target.dead?  
    "#{name.titleize} attacked #{target.name.titleize} for #{attack} damage," 
end 

要調用內部attack和內strength方法strength

def strength 
    amount * attack ## << -- No arguments here 
end 

您從strength方法,你在哪裏不帶任何參數調用attack收到錯誤。

@amount@attack實例變量已爲其定義使用attr_accessor getter和setter方法。 所以,@attack你現在有兩種方法,attackattack=

記住

There may be only one method with given name in Ruby class. If several methods with the same name defined in the class - the latest overwrites previous definitions.

所以,當你定義attack(target)與參數的訪問方法attack被覆蓋。現在,您只剩下兩種方法attack(target)attack=

+0

金額和攻擊是實例變量 – manis

+1

'@ amount'和'@ attack'是實例變量。數量和攻擊是方法。 –

+0

啊當然,謝謝 – manis

相關問題