Like many object-oriented languages, Ruby has separation between methods in the class context and those in the instance context:
class Example
def self.a_class_method
"I'm a class method!"
end
def an_instance_method
"I'm an instance method!"
end
end
When calling them using their native context it works:
Example.a_class_method
Example.new.an_instance_method
When calling them in the wrong context you get errors:
Example.new.a_class_method # => No such method
Example.an_instance_method # => No such method
Since an instance is related to a class you can do this:
Example.new.class.a_class_method # => Works!
That’s often done inside instance methods that need to use class methods. Class methods aren’t really able to utilize instance methods except if there’s an instance in play. When deciding to make a method, you often need to consider the context in which it will be used. If it’s instance related, especially if it uses @
-style instance variables, then it’s an instance method. If it’s a generic utility method that is intended to be used independent of any particular instance, it’s a class method.
In other languages the class methods are called “static” methods, they’re stand-alone basically, but in Ruby they actually relate to the class itself, which is a special object, so it can be a little confusing at times.
That’s why paying attention to the presence of self
in the definition is very important.
8
solved The most annoying quirk of class methods in ruby ever