Ruby journey (4) class inheritance

Source: Internet
Author: User

Go directlyCode
Rectangle. Rb

Class Rectangle
Attr_accessor: width
Attr_accessor: Height

Def Initialize (wdth, HgT)
@ Width = Wdth
@ Height = HgT
End

Def Area ()
Return @ Width * @ Height
End

Def   + (Addrectangle)
Return Area () + Addrectangle. Area ()
End
End

Square. Rb

Require " Rectangle "   # Or require "rectangle. RB"

Class Square < Rectangle
Def Initialize (size)
@ Width = Size
@ Height = Size
End
End

S = Square. New ( 2 )
Puts S. Area # Output 4

We can see that square inherits the rectangle class and has a new initalize method.
In this way, you can remember two things. One is the inherited symbol <, and the other is that the require method can contain another Ruby source file.

In Ruby, the method definition can be placed outside the class, for example

Def Fell? ()
Puts " I fell fine. "
End
Fell? ()

This method seems to be a global function. Instead of a global function, it adds a fell to the base class object? Method, because any class is inherited from the object, so at this time, any class will support this fell? Method.

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.