Ruby notes object-based Class)

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.