Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private method called error

Tags:

ruby

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)
like image 760
pdenlinger Avatar asked Jun 09 '11 19:06

pdenlinger


People also ask

Does Ruby have private methods?

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 .

How do you call a private method in Ruby?

Using BasicObject#instance_eval , you can call private method.

Which Ruby method can be used to call a method defined as private in the class?

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.

What is no method error in Ruby?

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...


1 Answers

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.)

like image 82
Chuck Avatar answered Sep 28 '22 12:09

Chuck