Ruby object-oriented programming methods and class extensions, ruby object-oriented programming
Class method
The essence of a class method is a single-piece method that lives in a single-piece class of that class. There are three definition methods, namely:
# Law one
def MyClass.a_class_method; end
# Law two
class MyClass
def self.anther_class_method; end
end
# Law three *
class MyClass
class << self
def yet_another_class_method; end
end
end
Among them, the third method is revealed, the essence of the class method, especially remember!
Class extension
Class extensions define class methods by adding modules to the single-piece class of the class.
module MyModule
def my_method; ‘hello '; end
end
class MyClass
class <self
include MyModule
end
end
MyClass.my_method
The above code shows the implementation of the concrete class extension. A MyModule module is introduced into the single-class class of the MyClass class, because the my_method method is an instance method of the single-class class of MyClass.
Object extension
Class methods are special cases of single-piece methods, so you can apply the technique of class extension to any object. This technique is object extension
# Method one: open a single class to expand
module MyModule
def my_method; ‘hello '; end
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
#Object extension
obj.extend MyModule
obj.my_method # => “hello”
#Class extension
class MyClass
extend MyModule
end
MyClass.my_method # => “hello”
Object # extend is a shortcut method for including modules in the receiver's singleton class.