2012-11-15 46 views
2

我有這個類:數學與實例變量

class Account 
    attr_accessor :balance 
    def initialize(balance) 
      @balance = balance 
    end 
    def credit(amount) 
      @balance += amount 
    end 
    def debit(amount) 
      @balance -= amount 
    end 
end 

然後,例如,在後來的程序:

bank_account = Account.new(200) 
bank_account.debit(100) 

如果我打電話用的借記法「 - =」運營商它(如上面的類)的程序失敗,出現以下消息:

bank2.rb:14:in `debit': undefined method `-' for "200":String (NoMethodError) 
from bank2.rb:52:in `<main>' 

但是,如果我去掉負號,並只讓@bal ance =金額,那麼它工作。顯然我想要它減去,但我不明白爲什麼它不起作用。數學不能用實例變量來完成嗎?

回答

3

傳入initialize()的值是一個字符串,而不是一個整數。通過.to_i將其轉換爲int。

def initialize(balance) 
    # Cast the parameter to an integer, no matter what it receives 
    # and the other operators will be available to it later  
    @balance = balance.to_i 
end 

同樣地,如果傳遞給debit()credit()所述參數是一個字符串,它轉換爲int。

def credit(amount) 
    @balance += amount.to_i 
end 
def debit(amount) 
    @balance -= amount.to_i 
end 

最後,我要補充一點,如果你打算設置@balanceinitialize()方法外,建議定義其二傳手叫.to_i含蓄。

def balance=(balance) 
    @balance = balance.to_i 
end 

注意:這裏假定您只想要使用整數值。如果您需要浮點值,請使用.to_f

+0

強制轉換離子總是一個好主意,因爲它允許你使用非數字的東西,但如果你問得好,*可能是數字。 – tadman

+0

邁克爾 - 你的評論,我傳遞一個字符串到initialize()讓我意識到我的問題在哪裏。我在我的問題中使用了一個例子,但我實際上創建一個新類的方式來自於一個參數(ARGV)。當我運行該程序時,我輸入類似「ruby bank2.rb 1000」的內容,然後用1000作爲餘額創建一個新賬戶。所以我現在的猜測是,也許參數總是作爲字符串讀入,這就是我的整個String問題來自的地方。除了initialize()以外,我在其他地方使用.to_i。今天下班後我會試一試。 – cliff900

+0

@ cliff900是的,ARGV總是保存字符串。 –

0

嘗試

def credit(amount) 
     @balance += amount.to_i 
end 
def debit(amount) 
     @balance -= amount.to_i 
end 

或通過一些作爲參數(錯誤說,你是傳遞一個字符串),最有可能的

+0

謝謝。實際上,我將這個值傳遞給這樣的借記方法:'code'bank_account.debit(amount.to_i)'code',我認爲它會起作用。不過,我想我在最後回答中留下的評論中發現了我的問題。 – cliff900

3

,你做

bank_account = Account.new("200") 

你實際上應該做

bank_account = Account.new(200)