This note is used to help understand the "<" command
The ruby language allows us to define classes based on an object so that we can expand the behavior of an object separately. The example is as follows:
Test = "hello" # normal string
Normal = A. DUP # normal string
Class <Test
Def to_s
"Value is # {self }"
End
End # The test object has been updated and normal remains unchanged.
After running the above Code
Normal. to_s = "hello"
Test. to_s = "value is hello"
In this example, the class of the test object has been extended to the new to_s method, but this extension can only affect the test object itself, and other string objects are still the original method.
My understanding: the object-based class is defined by the Instruction "<". It can be extended and can only be extended to the defined object, but cannot affect other objects of the same type in the system.
"<" Command can be used to temporarily modify an object. In addition, this command can also be used to define class methods. Generally, the following syntax is used to define class methods:
Class Test
Def test. Say
"Hello"
End
End
If you need to write the class name multiple times, you can replace it with self.
Class Test
Def self. Say
"Hello"
End
End
With the "<" command, you can also
Class Test
Class <self
Def say
"Hello"
End
End
End
The definitions of the above three are equivalent, and it is easy to see the third usage in Ruby source code.
Explanation: In Ruby, each class has a unique metaclass instance. The method defined by the class exists in this metaclass.
Using "<" to extend metaclass of this unique instance, adding methods to metaclass is the same effect as directly adding methods to this class.