This is a question of OOP than ruby. Class methods in ruby are used in the same way as in other OO programming languages. It means:
- class methods are executed in the context of the class (and have access only to class variables)
- instance methods are executed in the context of the object (and have access to the variables of the object or instance).
Here is a better example:
class Foo def self.bar puts 'class method' end def baz puts 'instance method' end end Foo.bar
Here you can see that the class method is accessible through the class, and the instance method is accessible through the instance or class object ( Foo.new ).
An example is copied from here , where you can also find additional information on this subject.
Keep in mind: although any code can be placed in a class or instance method, each has its own use cases and its own pros and contrasts. In OOP, we strive for reusable, flexible, and readable code, which means that we usually want to put most of the code structured as instance methods in a reasonable domain model.
source share