add a protected method to a class in ruby

To add a protected method to a class in Ruby, you can use the protected keyword followed by the definition of your method. This will make the method only accessible from within the class and its subclasses. Here is an example:

main.rb
class MyClass
  def my_public_method
    puts "This is a public method"
  end
  
  protected # all methods defined after this keyword will be protected
  
  def my_protected_method
    puts "This is a protected method"
  end
end
229 chars
12 lines

In the example above, my_public_method is a public method that can be called outside the class, whereas my_protected_method is a protected method that can only be called from within the class or its subclasses.

By using protected methods, you can encapsulate certain parts of your class's behavior and prevent them from being called from external code. This helps to make your code more modular and maintainable.

gistlibby LogSnag