私有方法称为错误

时间:2011-06-09 19:03:19

标签: ruby

写了一个方法;当我尝试运行它时,我收到错误:

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)

3 个答案:

答案 0 :(得分:23)

当你在任何类之外声明一个方法时,它是一个私有方法,这意味着它不能在其他对象上调用。您应该打开您希望该方法进入的类,然后将方法定义放在那里。 (如果你想要它在多个类中,要么打开一个公共超类,要么将它放在一个模块中,并在所有类中包含该模块。)

答案 1 :(得分:4)

您的意思是将方法subtotal包含在任何类中吗? E.g。

class Numeric
  def subtotal(qty = 1)
    return nil if self.to_f <= 0 || qty.to_f <= 0
    self.to_f * qty.to_f
  end
end

答案 2 :(得分:0)

我正在看这个,看到你似乎在包含subtotal类的变量上调用Float方法。这相当于Float.subtotal。现在,问题很容易看出来。您尚未将小计方法定义为Float类的一部分。

相关问题