Ruby way the second of OOP

Source: Internet
Author: User

1 Understanding Allocate

In some special environments, you may want to create an object without invoking its constructor (i.e., initialize). That is, you want to create an empty object. For example, suppose you have an object whose state is completely determined by its access method, so it is not necessary to invoke the new method if you do not really want an additional state. At this point we can allocate the method.

Ruby Code

Class Person
Attr_accessor:name,: Age,:p hone
def initialize (n,a,p)
@name, @age, @phone = N, A, p
End
def test
P "triple-A" end
p1 = person.new ("John Smith", "555-1234")
P2 = person.allocate
P p1.age #
P p2.age # nil
p2.test    

2 Modules

There are two reasons to use modules in Ruby. The first reason is namespace management, when we store constants and methods in module, we will have fewer naming conflicts. The method and class method in the Invoke module is very similar to the module name + method name. So let's see To File.ctime and filetest.exist, when we cannot know from the surface whether file and Filetest are modules or classes.

The second reason is more interesting, we can use the module to carry on the mixin. about what is mixin, don't say it.

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.