To add a private method to a class in Ruby, you can use the private
keyword to declare the method as private within the class definition. Here's an example:
main.rb174 chars12 lines
In this example, the private
keyword is used to declare the private_method
as private. This means that it can only be called from within the class, and not from outside of the class.
To call the private method from within the class, you can simply call it like any other method:
main.rb48 chars3 lines
When you call public_method
on an instance of MyClass
, it will output:
main.rb49 chars3 lines
Note that calling private_method
from outside of the class will result in a NoMethodError
, since it can only be called from within the class.
gistlibby LogSnag