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

In Ruby, to call a private property on an instance of a class, you need to define a getter method within the class that returns the private property.

Here's an example:

main.rb
class MyClass
  def initialize
    @foo = "private property"
  end
  
  private
  
  def foo
    @foo
  end
end

my_instance = MyClass.new
puts my_instance.send(:foo) # Output: private property
194 chars
15 lines

In the example above, foo is a private property of MyClass. To access the value of foo on an instance of the class, we define a foo method that returns the value of @foo. We then call this method using the send method on the instance, passing in :foo (as a symbol) as the method name.

Note that this technique is generally considered bad practice, as private properties are meant to be inaccessible from outside the class.

gistlibby LogSnag