call a protected property on an instance of a class in ruby

To call a protected property on an instance of a class in Ruby, you can create a public method within the class that returns the value of the protected property. Here is an example:

main.rb
class MyClass
  def initialize
    @my_protected_property = "Hello, world!"
  end

  def get_protected_property
    @my_protected_property
  end

  protected
  attr_reader :my_protected_property
end

my_instance = MyClass.new
puts my_instance.get_protected_property # Outputs "Hello, world!"
292 chars
16 lines

In this example, the MyClass has a protected property called my_protected_property. We define a method get_protected_property within the class, which is public and returns the value of the protected property.

When we create an instance of MyClass and call get_protected_property on it, we are able to access and output the value of the protected property.

Note that using a public method to access a protected property is a common practice in Ruby to maintain the encapsulation principle of object-oriented programming.

gistlibby LogSnag