已经写了一个方法;当我尝试运行它,我得到的错误:称为错误的私有方法
NoMethodError: private method ‘subtotal’ called for 39.99:Float
at top level in grades.rb at line 9
Program exited with code #1 after 0.04 seconds.
以下是代码:
def subtotal(qty = 1)
return nil if self.to_f <= 0 || qty.to_f <= 0
self.to_f * qty.to_f
end
book = 39.99
car = 16789
puts book.subtotal(3)
puts car.subtotal
puts car.subtotal(7)
问题:如果我没有定义类,它不应该默认为对象类?那是我对Ruby会做什么的理解。这种理解是不正确的? – pdenlinger 2011-06-09 19:52:33
@pdenlinger:这是正确的,但它将其定义为Object的*私有方法*。它不仅仅是一个默认范围 - 它是一种特殊的行为,旨在模仿像Python这样的语言来定义函数。 – Chuck 2011-06-09 20:08:15
知道了!非常感谢你的解释。 – pdenlinger 2011-06-10 00:05:57