A class method is also called a static method. It is called by class name. Instance method. You must create a new instance before using it.
Class Foo def self. bar puts 'class method' end def Baz puts 'instance method' endendfoo. bar # class method # Foo. baz # error: Undefined method 'baz' For foo: Class (nomethoderror) Foo. new. baz # instance method # Foo. new. bar # error: Undefined method 'bar' for # <0x2d61a1c> (nomethoderror)
In this example, bar is the class method, and how it is defined: def self. Bar, self is the point to the current class. The instance method is simple: def Baz.
A flexible scripting language like Ruby is rare. It provides a variety of methods for defining class methods.
# way 1 class Foo def self. bar puts 'class method' endendfoo. bar # "class method" # way 2 class Foo class the first and third methods are not described in detail. The use of self is equivalent to the use of JavaScript this. The second has the meaning of self-inheritance. It is very elegant to write less self when we add multiple class methods.
let's look at the instance method. There are also several solutions:
# way 1 class Foo def Baz puts 'instance Method1 'endendfoo. new. baz # "instance Method1" puts '-------------' # way 2 class Foo attr_accessor: bazendfoo = Foo. newfoo. baz = 'instance method2 'puts Foo. baz # "instance method2" puts '-------------' # way 3 class Foo; endfoo = Foo. newdef Foo. lazy puts 'instance method3 'endfoo. Lazy # "instance method3"
the first is a direct definition, the second is the attr_accessor syntax, and the third is the late binding, this method is only valid for that instance.