add a private method to a class in ruby

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.rb
class MyClass
  def public_method
    puts "This is a public method"
    private_method
  end
  
  private
  def private_method
    puts "This is a private method"
  end
end
174 chars
12 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.rb
my_object = MyClass.new
my_object.public_method
48 chars
3 lines

When you call public_method on an instance of MyClass, it will output:

main.rb
This is a public method
This is a private method
49 chars
3 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