Class method
The essence of a class method is a single piece method that lives in a single piece of the class. There are three ways to define them, respectively:
# method One
def Myclass.a_class_method end
# Two
class MyClass
def self.anther_class_method
# Method III *
class MyClass
class << self
def yet_another_class_method
The third way out, the essence of the class method, special memory!
Class extension
Class extensions define class methods by adding modules to the class's monolithic classes.
Module MyModule
def My_method; ' Hello '; End
-
class MyClass
class < self
include mymodule
end
myclass.my_ Method
The code above shows the implementation of the specific class extension, introducing a MyModule module into the MyClass class, because the My_method method is an instance method of the MyClass Singleton class, so the My_method method is also a MyClass class method.
Object extension
A class method is a special case of a single piece of method, so it is possible to apply a class extension to any object, which is an object extension
# method One: Open a single piece class to extend
module MyModule
def My_method; ' Hello '; End
' obj = object.new
class << obj
include mymodule
end
Obj.my_method # => Hello "
obj.singleton_methods # => [: My_method]
# Method Two: Object#extend method
Module MyModule
def My_method; ' Hello '; End
End
obj = object.new
#对象扩展
obj.extend mymodule
obj.my_method # => "Hello"
#类扩展
class MyClass
extend MyModule
end
Myclass.my_method # => "Hello"
Object#extend is a fast-key way of including modules in the recipient's single piece class.