写了一个方法; 当我尝试运行它时,我收到错误:
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.
Run Code Online (Sandbox Code Playgroud)
以下是代码:
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)
Run Code Online (Sandbox Code Playgroud)
Chu*_*uck 24
当您在任何类之外声明一个方法时,它是一个私有方法,这意味着它不能在其他对象上调用.您应该打开您希望该方法进入的类,然后将方法定义放在那里.(如果你想要它在多个类中,要么打开一个公共超类,要么将它放在一个模块中,并在所有类中包含该模块.)