call a private static method on an instance of a class in ruby

In Ruby, private methods can not be called using an explicit receiver. However, there is a way you can call private static methods on instances of a class. This involves using the send method to call the private static method on an instance.

Here is an example:

main.rb
class MyClass
  def initialize(name)
    @name = name
  end
  
  private
  
  def self.private_method
    "This is a private static method"
  end
end

obj = MyClass.new("John")
puts obj.send(:private_method) #=> This is a private static method
244 chars
15 lines

In this example, we define a class MyClass with a private static method private_method. We then create an instance of the class and use the send method to call the private method on the instance.

Note that using send to call private methods can be risky as it bypasses Ruby's access control mechanisms. Use it with caution.

gistlibby LogSnag