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

In order to call a static method on an instance of a class in Ruby, you can simply prepend the class name to the method name. Here is an example:

main.rb
class MyClass
  def self.my_static_method
    puts "This is a static method."
  end
end

instance = MyClass.new
MyClass.my_static_method # Calling static method on class
instance.class.my_static_method # Calling static method on instance using the class
254 chars
10 lines

In the example above, we define a MyClass which has a static method my_static_method. We then create an instance of MyClass called instance.

To call my_static_method on the class itself, we simply use the class name followed by the method name, like this: MyClass.my_static_method.

To call the same method on an instance of the class, we can access the instance's class attribute, which points to the class, and then call the method using the class name, like this: instance.class.my_static_method.

gistlibby LogSnag