Basic tutorial of Ruby object-oriented programming, ruby Object-Oriented Programming

Source: Internet
Author: User

Basic tutorial of Ruby object-oriented programming, ruby Object-Oriented Programming

Ruby is a pure object-oriented language, and everything in Ruby is in the form of objects. Every value in Ruby is an object, even the most primitive: String, number, or even true or false are objects. The Class itself is also an object and an instance of the Class. This chapter describes all main Ruby object-oriented functions.

Class is used to specify the form of an object. It combines the data representation method and method to organize the data into a neat package. The data and methods in the class are called members of the class.
Ruby class definition

When you define a category, you actually define a blueprint for the data type. This does not actually define any data, but defines what the class name means, that is, what the class object will be composed of and what operations can be performed on the object.

The class definition starts with the keyword class, followed by the class name, and ends with an end to terminate the class definition. For example, we use the keyword class to define the Box class, as shown below:

class Box  codeend

By convention, the name must start with an uppercase letter. If multiple words are contained, the first letter of each word is capitalized, but there is no separator (for example, CamelCase) between them ).
Define Ruby objects

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

box1 = Box.newbox2 = Box.new

Initialize Method

The initialize method is a standard Ruby class method, which works similar to constructor in other object-oriented programming languages. The initialize method is useful when you want to initialize some class variables while creating objects. This method has a series of parameters. Like other Ruby methods, when using this method, the def keyword must be placed before it, as shown below:

class Box  def initialize(w,h)   @width, @height = w, h  endend

Instance variables

Instance variables are class attributes. They become the attributes of objects when they are created using classes. Each object's attribute is assigned a value separately and is not shared with other objects. Inside the class, the @ operator is used to access these attributes. Outside the class, the public method called the accessor method is used for access. The class Box defined above is an instance, and @ width and @ height are used as the instance variables of the class Box.

Class Box def initialize (w, h) # assign @ width, @ height = w, h endend to the instance variable

Accessor & settingmethod

To use variables outside the class, we must define these variables within the accessors method, which is also called the accessors method. The following example demonstrates the usage of the accessor method:

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # accesser method def printWidth @ width end def printHeight @ height endend # create object box = Box. new (10, 20) # Use the accessor method x = box. printWidth () y = box. printHeight () puts "Width of the box is: # {x}" puts "Height of the box is: # {y }"

When the above code is executed, it will produce the following results:

Width of the box is : 10Height of the box is : 20

Similar to the method used to access variable values, Ruby provides a way to set variable values outside the class, that is, the so-called setter method, which is defined as follows:

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # accessor method def getWidth @ width end def getHeight @ height end # setWidth = (value) @ width = value end def setHeight = (value) @ height = value endend # create an object box = Box. new (10, 20) # Use 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 is executed, it will produce the following results:

Width of the box is : 30Height of the box is : 50

Instance method

Like other methods, instance methods use the def keyword, but they can only be used by class instances, as shown in the following example. They are not limited to accessing instance variables, but can also perform more tasks as needed.

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # instance method def getArea @ width * @ height endend # create object box = Box. new (10, 20) # Call the instance method a = box. getArea () puts "Area of the box is: # {a}" when the above code is executed, it will produce the following results: Area of the box is: 200 class methods & class variables are shared among all instances of the class. In other words, an instance with a class variable can be accessed by all object instances. The class variable is prefixed with two @ characters (@). The class variable must be initialized in the class definition, as shown in the following example. The class method is defined by def self. methodname (). The class method ends with the end separator. Class methods can be called in the form of classname. methodname with the class name, as shown in the following example :#! /Usr/bin/ruby-w class Box # initialization class variable @ count = 0 def initialize (w, h) # assign a value to the instance variable @ width, @ height = w, h @ count + = 1 end def self. printCount () puts "Box count is: # @ count" endend # create two objects box1 = Box. new (10, 20) box2 = Box. new (30,100) # Call the class method to output the Box count Box. printCount ()

When the above code is executed, it will produce the following results:

Box count is : 2

To_s Method

Any class you define has a to_s instance method to return the string representation of the object. The following is a simple example, indicating the Box object according to width and height:

#! /Usr/bin/ruby-w class Box # constructor method def initialize (w, h) @ width, @ height = w, h end # define the to_s method def to_s "(w: # @ width, h: # @ height)" # The string format endend of the object # create an object box = Box. new (10, 20) # automatically call the to_s method puts "String representation of box is: # {box }"

When the above code is executed, it will produce the following results:

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

Access Control

Ruby provides three levels of instance method protection: public, private, and protected. Ruby does not apply any access control on instances and class variables.

  • Public method: the Public method can be called by any object. By default, all methods are public, except that the initialize method is always private.
  • Private method: the Private method cannot be accessed or viewed from outside the class. Only class methods can access private members.
  • Protected method: the Protected method can only be called by objects of the class and its subclass. The access can only be performed within the class and its subclass.

The following is a simple example to demonstrate the syntax of these three modifiers:

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # The default instance method is the public def getArea getWidth () * getHeight end # defines the private accesser method def getWidth @ width end def getHeight @ height end # make them private: getWidth,: getHeight # instance method def printArea @ area = getWidth () * getHeight puts "Big box area is: # @ area "end # Make the instance method protected: printAreaend # create the object box = Box. new (10, 20) # Call the instance method a = box. getArea () puts "Area of the box is: # {a}" # try to call the protected instance method box. printArea ()

When the above code is executed, it will produce the following results. Here, the first method is called successfully, but the second method will produce a problem.

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

Class inheritance

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 code reuse and quick execution. Unfortunately, Ruby does not support multi-inheritance, but Ruby supports mixins. Mixin is like a specific implementation of multi-inheritance. In multi-inheritance, only the Interface part can be inherited.

When creating a class, the programmer can directly specify that the new class inherits from an existing class member, so that the new data member and member function do not need to be written from the beginning. This existing class is called a base class or parent class, and the new class is called a derived class or subclass.

Ruby also provides the subclass concept, that is, inheritance. The following example explains this concept. The syntax for extending a class is very simple. You only need to add a <character and parent class name to the class statement. For example, BigBox is a subclass of Box:

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # instance method def getArea @ width * @ height endend # define subclass class BigBox <Box # Add a new instance method def printArea @ area = @ width * @ height puts "Big box area is: # @ area "endend # create an object box = BigBox. new (10, 20) # Output Area box. printArea ()

When the above code is executed, it will produce the following results:

Big box area is : 200

Method overload

Although you can add new functions to a derived class, you may want to change the behavior of methods already defined in the parent class. In this case, you can reload the method function without changing the method name, as shown in the following example:

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # instance method def getArea @ width * @ height endend # define the subclass class BigBox <Box # change the existing getArea method def getArea @ area = @ width * @ height puts "Big box area is: # @ area "endend # create an object box = BigBox. new (10, 20) # Use the overload method to output the Area box. getArea ()

Operator overload

We want to use the + operator to perform Vector Addition of two Box objects, use the * operator to multiply the width and height of the Box, and use the unary operator-to reverse the width and height of the Box. The following is a Box class version with mathematical operators defined:

Class Box def initialize (w, h) # initialize width and height @ width, @ height = w, h end def + (other) # define + to execute vector addition Box. new (@ width + other. width, @ height + other. height) end def-@ # defines the unary operator-to reverse the Box of width and height. new (-@ width,-@ height) end def * (scalar) # execute the scalar multiplication Box. new (@ width * scalar, @ height * scalar) endend

Freeze object

Sometimes we want to prevent objects from being changed. In an Object, the freeze method can achieve this. It can effectively convert an Object into a constant. Any Object can be frozen by calling Object. freeze. The frozen object cannot be modified, that is, you cannot change its instance variables.

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

#! /Usr/bin/ruby-w # class definition Box # constructor method def initialize (w, h) @ width, @ height = w, h end # accessor method def getWidth @ width end def getHeight @ height end # setWidth = (value) @ width = value end def setHeight = (value) @ height = value endend # create an object box = Box. new (10, 20) # Let's freeze this object box. freezeif (box. frozen? ) Puts "Box object is frozen object" else puts "Box object is normal object" end # Now try to use 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 is executed, it will produce the following results:

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

Class constant

You can define a constant within the class by assigning a direct value or string value to a variable. The definition of a constant does not need to be @ or @@. By convention, the constant name is capitalized.

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

#! /Usr/bin/ruby-w # class definition class Box BOX_COMPANY = "TATA Inc" BOXWEIGHT = 10 # constructor method def initialize (w, h) @ width, @ height = w, h end # instance method def getArea @ width * @ height endend # create an object box = Box. new (10, 20) # Call the instance method a = box. getArea () puts "Area of the box is: # {a}" puts Box: BOX_COMPANYputs "Box weight is :#{ Box: BOXWEIGHT }"

When the above code is executed, it will produce the following results:

Area of the box is : 200TATA IncBox weight is: 10

Class constants can be inherited or overloaded like instance methods.
Use allocate to create an object

You may want to create an object without calling the object constructor initialize, that is, using the new method to create an object. In this case, you can call allocate to create an uninitialized object, as shown in the following example:

#! /Usr/bin/ruby-w # class definition class Box attr_accessor: width,: height # constructor method def initialize (w, h) @ width, @ height = w, h end # instance method def getArea @ width * @ height endend # Use new to create an object box1 = Box. new (10, 20) # Use allocate to create two objects box2 = Box. allocate # Use box1 to call the instance method a = box1.getArea () puts "Area of the box is: # {a}" # Use box2 to call the instance method a = box2.getArea () puts "Area of the box is: # {}"

When the above code is executed, it will produce the following results:

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

Class Information

If the class definition is executable code, it means that they can be executed in the context of an object, and self must reference something. Let's take a look at the following example :.

#! /Usr/bin/ruby-w class Box # output class information puts "Type of self =#{ self. type} "puts" Name of self = # {self. name} "end

When the above code is executed, it will produce the following results:

Type of self = ClassName of self = Box

This means that the class definition can be executed by using the class as the current object. It also means that the method in the Meta class and parent class is available during the execution of the method definition.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.