In Ruby, there are no static methods like in other programming languages. However, you can use class methods which are similar. Class methods belong to the class itself, rather than to any instance of the class. They are defined using the self
keyword.
To call a public class method on an instance of a class, you can use the class name followed by the method name, like so:
main.rb243 chars11 lines
In this example, we define a class method called my_class_method
on the MyClass
class using def self.
. We then create an instance of MyClass
called my_instance
.
To call the class method on the class itself, we simply use the class name, followed by the method name: MyClass.my_class_method
. To call the same method on an instance of the class, we first get the class of the instance using my_instance.class
, and then call the class method using .my_class_method
as before: my_instance.class.my_class_method
.
gistlibby LogSnag