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
  code
end

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.new
box2 = 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
  end
end

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 values to instance variables
    @width, @height = w, h
   end
end

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
 
# Define class
class Box
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
 
   # Accessor method
   def printWidth
    @width
   end
 
   def printHeight
    @height
   end
end
 
# Create object
box = Box.new (10, 20)
 
# Using 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
 
# Define class
class Box
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
 
   # Accessor method
   def getWidth
    @width
   end
   def getHeight
    @height
   end
 
   # Setter method
   def setWidth = (value)
    @width = value
   end
   def setHeight = (value)
    @height = value
   end
end
 
# Create object
box = Box.new (10, 20)
 
# Use the setter method
box.setWidth = 30
box.setHeight = 50
 
# Using 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
 
# Define class
class Box
  # constructor method
  def initialize (w, h)
   @width, @height = w, h
  end
  # Instance method
  def getArea
   @width * @height
  end
end
 
# Create object
box = Box.new (10, 20)
 
# Call instance method
a = box.getArea ()
puts "Area of the box is: # {a}"

When the above code is executed, it produces the following results:
Area of the box is: 200
Class methods & class variables

Class variables are variables that are shared across all instances of a class. In other words, instances of class variables can be accessed by all object instances. Class variables are prefixed with two @ characters (@@). Class variables must be initialized in the class definition, as shown in the following example.

Class methods are defined using def self.methodname (), and class methods end with an end delimiter. Class methods can be called using classname.methodname with the class name, as shown in the following example:
#! / usr / bin / ruby -w
 
class Box
  # Initialize class variables
  @@ count = 0
  def initialize (w, h)
   # Assign values to instance variables
   @width, @height = w, h
 
   @@ count + = 1
  end
 
  def self.printCount ()
   puts "Box count is: # @@ count"
  end
end
 
# Create two objects
box1 = Box.new (10, 20)
box2 = Box.new (30, 100)
 
# Call class method to output 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)" # String format of the object
   end
end
 
# Create 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
 
# Define class
class Box
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
 
   # Instance methods are public by default
   def getArea
    getWidth () * getHeight
   end
 
   # Define private accessor methods
   def getWidth
    @width
   end
   def getHeight
    @height
   end
   # make them private
   private: getWidth,: getHeight
 
   # Example method for output area
   def printArea
    @area = getWidth () * getHeight
    puts "Big box area is: # @ area"
   end
   # Make instance methods protected
   protected: printArea
end
 
# Create object
box = Box.new (10, 20)
 
# Call instance method
a = box.getArea ()
puts "Area of the box is: # {a}"
 
# Try to call 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 : 200
test.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
 
# Define class
class Box
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
   # Instance method
   def getArea
    @width * @height
   end
end
 
# Define subclasses
class BigBox <Box
 
   # Add a new instance method
   def printArea
    @area = @width * @height
    puts "Big box area is: # @ area"
   end
end
 
# Create 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
 
# Define class
class Box
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
   # Instance method
   def getArea
    @width * @height
   end
end
 
# Define subclasses
class BigBox <Box
 
   # Change existing getArea method
   def getArea
    @area = @width * @height
    puts "Big box area is: # @ area"
   end
end
 
# Create object
box = BigBox.new (10, 20)
 
# Output area using overloaded method
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 perform vector addition
   Box.new (@width + other.width, @height + other.height)
  end
 
  def-@ # define unary operator-to negate width and height
   Box.new (-@ width,-@ height)
  end
 
  def * (scalar) # perform scalar multiplication
   Box.new (@ width * scalar, @ height * scalar)
  end
end

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
 
# Define class
class Box
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
 
   # Accessor method
   def getWidth
    @width
   end
   def getHeight
    @height
   end
 
   # Setter method
   def setWidth = (value)
    @width = value
   end
   def setHeight = (value)
    @height = value
   end
end
 
# Create object
box = Box.new (10, 20)
 
# Let's freeze the object
box.freeze
if (box.frozen?)
   puts "Box object is frozen object"
else
   puts "Box object is normal object"
end
 
# Now try the setter method
box.setWidth = 30
box.setHeight = 50
 
# Using 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 object
test.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
 
# Define class
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
   end
end
 
# Create object
box = Box.new (10, 20)
 
# Call instance method
a = box.getArea ()
puts "Area of the box is: # {a}"
puts Box :: BOX_COMPANY
puts "Box weight is: # {Box :: BOXWEIGHT}"

When the above code is executed, it will produce 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.
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
 
# Define class
class Box
   attr_accessor: width,: height
 
   # Constructor method
   def initialize (w, h)
    @width, @height = w, h
   end
 
   # Instance method
   def getArea
    @width * @height
   end
end
 
# Create object with new
box1 = Box.new (10, 20)
 
# Create two objects using allocate
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: # {a}"

When the above code is executed, it will produce 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

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

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.