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.