2012-11-15 44 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)