Have written a method; when I try to run it, I get the error:
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.
Following is the code:
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
put开发者_JS百科s book.subtotal(3)
puts car.subtotal
puts car.subtotal(7)
When you declare a method outside of any class, it's a private method, which means it can't be called on other objects. You should open the class that you want the method to go into and then put the method definition in there. (If you want it in multiple classes, either open a common superclass or put it in a module and include that module in all the classes.)
Do you mean to include the method subtotal
into any class? 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
I'm looking at this and seeing that you seem to be calling the subtotal
method on a variable containing of the Float
class. This is equivalently Float.subtotal
. Now, the problem is easy to see then. You haven't defined the subtotal method as part of the Float class.
精彩评论