Ruby object oriented


Release date:2023-11-01 Update date:2023-11-02 Editor:admin View counts:362

Label:

Ruby object oriented

Ruby is a pure object-oriented language, and everything in Ruby appears in the form of objects. Every value in Ruby is an object, even the most primitive thing: strings, numbers, even true and false . They’re alldates. The class itself is also an object, and is Class an instance. This chapter will show you all the main features related to Ruby object orientation.

Class is used to specify the form of the object, which combines data representations and methods to organize the data into a neat package. The data and methods in a class are called members of the class.

Ruby class definition

When you define a class, you are actually defining a blueprint for a data type. This does not actually define any data, but rather what the name of the class means, that is, what the object of the class will consist of and what actions can be performed on that object.

Class is defined with keywords class start, followed by the class name,and finally with a end delimiting means terminating the class definition. For example, we use keywords class to define the Box class,as follows:

classBoxcodeend

By convention, the name must start with an uppercase letter, and if it contains more than one word, the first letter of each word is capitalized, but there is no delimiter (for example: CamelCase).

Define Ruby object

Class provides a blueprint for the object, so basically, the object is created from the class. We use new keyword declares the object of the class. The following statement declares two objects of class Box:

box1=Box.newbox2=Box.new

Initialize method

initialize method is a standard Ruby class method, which is the constructor of the class, which is similar to the constructor . It works in a similar way. When you want to initialize some class variables while creating an object initialize the method will come in handy. This method takes a series of parameters and, like other Ruby methods, must be placed in front of it def keyword, as follows:

classBoxdefinitialize(w,h)@width,@height=w,hendend

Instance variable

Instance variables are class properties, and they become properties of an object when you create an object using a class. The properties of each object are assigned separately and the values are not shared with other objects. Inside the class, you use the @ operators access these properties, and outside the class, they are accessed using public methods called accessor methods. Let’s use the class defined above Box as an example, set the @width and @height as a class Box the instance variable.

classBoxdefinitialize(w,h)#Assigning values to instance variables
@width,@height=w,hendend

Accessor (getter) & setter method

In order to read the variables defined in the class outside the class, we can access them by defining a getter method. The following example demonstrates the use of the accessor method:

Example

#!/usr/bin/ruby
-w# Defined Class classBox# Constructor definitialize(w,h)
@width,@height=w,hend# accessor method defprintWidth@widthenddefprintHeight
@heightendend# Create an object, initialize the height and width of the box box=Box.new(10,20)
#Using accessor methods x=box.printWidth()y=box.printHeight()puts"Box width
: #{x}"puts"Box width : #{y}"

When the above code executes, it produces the following results:

Box width : 10
Box height : 20

Similar to the accessor method used to access the value of a variable, Ruby provides a way to pass parameters to a defined variable in the class, known as the setter method, outside the class, defined as follows:

Example

#!/usr/bin/ruby
-w# Defined Class classBox# Constructor method definitialize(w,h)@width,@height=w,hend
# accessor method defgetWidth@widthenddefgetHeight@heightend
# Setter method defsetWidth=(value)@width=valueenddefsetHeight=(value)
@height=valueendend# create object box=Box.new(10,20)#Using the setter method
box.setWidth=30box.setHeight=50#Using accessor methods
x=box.getWidth()y=box.getHeight()puts"Box width
: #{x}"puts"Box height : #{y}"

When the above code executes, it produces the following results:

Box width : 30
Box height  : 50

Because the two methods are very common, Ruby defines the attr_accessor :variable_nameattr_reader :variable_nameattr_writer :variable_name , there are three methods of attribute declaration. Where: accessor=reader+writer .

At the same time, note: variable names must be preceded by:, should be used between variable names, division.

Example method

The definition of an instance method is the same as that of other methods, using the def keywords, but they can only be used by class instances, as shown in the following example. Their functions are not limited to accessing instance variables, but can also do more other tasks according to your needs.

Example

#!/usr/bin/ruby
-w# Defined Class classBox# Construction method definitialize(w,h)
@width,@height=w,hend# instance method defgetArea@width*@heightendend
#create object box=Box.new(10,20)#Calling Instance Methods a=box.getArea()puts"Area
of the box is : #{a}"

When the above code executes, it produces the following results:

Area of the box is : 200

Class method & Class variable

Class variables are variables that are shared among all instances of the class. In other words, instances of class variables can be accessed by all object instances. Class variables are represented by two @ character (@@ as a prefix, the class variable must be initialized in the class definition, as shown in the following example.

Class method use def self.methodname() definition, class methods to end the end of the delimiter. Class methods can use the classname.methodname form call, as shown in the following example:

Example

#!/usr/bin/ruby
-wclassBox#Initialize Class Variables @@count=0definitialize(w,h)
#Assigning values to instance variables @width,@height=w,h@@count+=1enddefself.printCount()puts"Box
count is :
#@@count"endend#Create two objects box1=Box.new(10,20)
box2=Box.new(30,100)#Calling class methods to output box count Box.printCount()

When the above code executes, it produces the following results:

Box count is : 2

To_s method

Any class you define has a to_s instance method to return a string representation of the object. Here is a simple example based on the width and height express Box object:

Example

#!/usr/bin/ruby
-wclassBox#Constructor method definitialize(w,h)@width,@height=w,hend#define to_s
method defto_s"(w:#@width,h:#@height)"#The string format of the object
end end#create object box=Box.new(10,20)#automatic call
to_s method puts"String representation of box is : #{box}"

When the above code executes, it produces the following results:

String representation of box is : (w:10,h:20)

access control

Ruby provides you with three levels of instance method protection, namely publicprivate or protected . Ruby does not apply any accesscontrol to instance and class variables.

  • Public Methods: Public method can be called by any object. By default, the methods are all public except for initialize , the method is always private .

  • Private methods: Private method cannot be accessed or viewed from outside the class. Only class methods can access private members.

  • Protected methods: Protected methods can only be called by objects of the class and its subclasses. Access can only be made within the class and its subclasses.

Here is a simple example that demonstrates the syntax of these three modifiers:

Example

#/ Usr/bin/ruby
-W # Define class classBox # Constructor method define (w, h) @ width, @ height=w, then # Instance method defaults to
The defgetAreageWidth() * getHeightend # of public defines private
Access method for defgetWidth@widthenddefgetHeight @Heightend # make them
Privateprivate: getWidth,
: getHeight # Instance method for outputting area defprintArea@area =GetWidth() * getHeightputs "Big
Box area is: # @ area "end # Make the instance method protected
Protected: printAreend # Create object box=Box. new (10,20) # Call instance method a=box. getArea() puts "Area
Of the box is: # {a} "# Attempting to call the protected instance method box. printArea()

When the above code is executed, it produces the following results. In this case, the first method is called successfully, but the second method createsa problem.

Area of the box is : 200
test.rb:42: protected method `printArea' called for #
<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)

Inheritance of class

Inheritance is one of the most important concepts in object-oriented programming. Inheritance allows us to define a class based on another class,which makes it easier to create and maintain applications.

Inheritance helps reuse code and execute quickly. Unfortunately, Ruby does not support multiple inheritance, but Ruby does mixins . mixin is like a specific implementation of multi-inheritance, in which only the interface part is inheritable.

When creating a class, the programmer can directly specify that the new class inherits from the members of an existing class, so that you don’t haveto write new data members and member functions from scratch. This existing class is called a base class or parent class, and a new class is called a derived class or subclass.

Ruby also provides the concept of subclassing, which is inheritance, which is explained by the following example. The syntax for extending a class is very simple. Just add a < character and the name of the parent class to the class statement. For example, the class is defined below BigBox is subclasses of: Box

Example

#/ Usr/bin/ruby
-W # Define class classBox # Constructor method define (w, h) @ width,
@ height=w, then # Instance method defgetArea@width *@Heightend # Define subclass classBigBox<Box
# Add a new instance method defprintArea@area =@Width * @ heightputs "Big
Box area is:
#@Area "end # Create object box=BigBox. new (10,20) # Output area box. printArea()

When the above code executes, it produces the following results:

Big box area is : 200

Method overload

Although you can add new functionality to a derived class, sometimes you maywant to change the behavior of a method that has been defined in the parentclass. At this point, you can keep the name of the method unchanged and overload the function of the method, as shown in the following example:

Example

#/ Usr/bin/ruby
-W # Define class classBox # Constructor method define (w, h) @ width, @ height=w, then # Instance method
defgetArea@width *@Heightend # Define subclass classBigBox<Box # Change existing
GetArea method defgetArea@area =@Width * @ heightputs "Big box area is:
#@Area "end # Create object box=BigBox. new (10,20) # Use overloaded methods to output area box. getArea()

The output of the above instance is as follows:

Big box area is : 200

Operator overloading

We want to use the + operator executes two Box object’s vector addition, using the * operator to put Box of width and height multiply, using the unary operator Box of width and height seek the opposite. The following is a definition of a mathematical operator Box class version:

ClassBoxdefine initialize (w, h) # Initialize width and
height@width , @ height=w, henddef+(other) # Definition+
To perform vector addition Box. new (@ width+other. width,
@ height+other. height) enddef - @ # Define unary operators
-To negate width and height Box.new (- @ width,
-@Height) enddef * (scalar) # Execute scalar multiplication
Box.new (@ width * scalar, @ height * scalar) endend

Freeze object

Sometimes we want to prevent the object from being changed. In Object freeze method can do this, which effectively turns an object into a constant. Any object can be called by calling the Object.freeze to freeze. The frozen object cannot be modified, that is, you cannot change itsinstance variable.

You can use the Object.frozen? method to check whether a given object has been frozen. If the object is frozen, the method returns true otherwise, a false value. The following example explains this concept:

Example

#/ Usr/bin/ruby
-W # Define class classBox # Constructor method define (w, h) @ width, @ height=w, then # Visitor
method defgetWidth@widthenddefgetHeight @Heightend # Setter method defsetWidth=(value) @
width=valueend defsetHeight=(value) @ height=valueend # Create object box=Box. new (10,20)
# Let's freeze the object box. freezeif (box. frozen?) puts "Box
Object is frozen object "elseputs" Box object is normal
Object "end # Now try using the setter method box. setWidth=30box. setHeight=50
# Use the accessor method x=box. getWidth() y=box. getHeight() puts" Width
Of the box is: # {x} "puts" Height of the box is: # {y}“

When the above code executes, it produces the following results:

Box object is frozen object
test.rb:20:in `setWidth=': can't modify frozen object (TypeError)
        from test.rb:39

Quasi constant

You can define a constant inside a class by assigning a direct numeric or string value to a variable. The definition of a constant does not need to beused. @ or @@ . By convention, the names of constants are capitalized.

Once a constant is defined, you cannot change its value. You can access the constant directly inside the class, just like an access variable, but if youwant to access the constant outside the class, you must use the classname::constant as shown in the following example

Example

#!/usr/bin/ruby -w#Define Class classBoxBOX_COMPANY="TATA
Inc"BOXWEIGHT=10#Constructor method definitialize(w,h)@width,@height=w,
hend#Example Method defgetArea@width*@heightendend#create object box=Box.new(10,20)
#Calling instance methods a=box.getArea()puts"Area
of the box is : #{a}"putsBox::BOX_COMPANYputs"Box weight is:
#{Box::BOXWEIGHT}"

When the above code executes, it produces the following results:

Area of the box is : 200
TATA Inc
Box weight is: 10

Class constants can be inherited or overloaded like instance methods.

Create objects using allocate

There may be a situation where you want to call the object constructor without calling initialize create an object in the case of, that is, using the new method, in which case you can call the allocate to create an uninitialized object, as shown in the following example :

Example

#!/usr/bin/ruby -w#Define Class classBoxattr_accessor:width,
:height#Constructor method definitialize(w,h)@width,
@height=w,hend#Example Method defgetArea@width*@heightendend#use
new create object box1=Box.new(10,20)#use allocate
Create another object box2=Box.allocate#use box1
Calling instance methods a=box1.getArea()puts"Area of the box is :
#{a}"#use box2
Calling instance methods a=box2.getArea()puts"Area of the box is : #{a}"

When the above code executes, it produces the following results:

Area of the box is : 200
test.rb:14: warning: instance variable @width not initialized
test.rb:14: warning: instance variable @height not initialized
test.rb:14:in `getArea': undefined method `*'
   for nil:NilClass (NoMethodError) from test.rb:29

Class information

Ruby’s self and Java’s this have similarities, but they are very different. Java methods are all referenced in instance methods, so this usually points to the current object. Ruby code executes line byline, so self has different meanings in different contexts (context). Let’slook at the following example:.

Example

#!/usr/bin/ruby -wclassBox#Output Class Information puts"Class of self =
#{self.class}"puts"Name of self = #{self.name}"end

When the above code executes, it produces the following results:

Class of self = Class
Name of self = Box

This means that the class definition can be executed by making the class thecurrent object, and that the method in the metaclass and parent class is available during the execution of the method definition.

Powered by TorCMS (https://github.com/bukun/TorCMS).