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
puts book.subtotal(3)
puts car.subtotal
puts car.subtotal(7)
Understanding Private Methods in Ruby You can only use a private method by itself. It's the same method, but you have to call it like this. Private methods are always called within the context of self .
Using BasicObject#instance_eval , you can call private method.
The keyword private tells Ruby that all methods defined from now on, are supposed to be private. They can be called from within the object (from other methods that the class defines), but not from outside.
Explained. This is a common Ruby error which indicates that the method or attribute for an object you are trying to call on an object has not been defined. For example, the String class in Ruby has the method size (which is synonymous with length , so I can write...
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With