Ruby object-oriented Programming Detailed _ruby topics

Source: Internet
Author: User
Tags class definition instance method scalar uppercase letter

Ruby is a purely object-oriented language, and all projects seem to be in Ruby as an object. Each value in Ruby is an object, even the most primitive thing: a string, a number, or even true and false. Even if a class itself is an object, it is an instance of class. This chapter will cover the object-oriented aspects of Ruby through all the features.

Class is used to specify the form of an object, combining data representations and methods to manipulate the data and convert it into a neat package. In a class of data and methods that are called members of a class.

Definition of Ruby class:

Define a class, a sketch of the data type defined. This does not actually define any data, but it defines what the class name means, that is, what class object will include such an object on what operations can be performed.

The class definition begins to be delimited with the keyword class name and end. For example, we define the box class using the Class keyword as follows:

Copy Code code as follows:

Class Box
Code
End

The name must start with an uppercase letter, with more than one word in the contract name, with no delimiters (hump-style) to execute for each word.

To define Ruby objects:

Class is the blueprint for an object, so basically a class object is created from it. We declare the object of a class to use the New keyword. The following statement declares two objects, the Box class:

Copy Code code as follows:

Box1 = Box.new
Box2 = Box.new

Initialize Method:

The Initialize method is a standard Ruby class method that works in the same way as other object-oriented programming languages. The Initialize method is useful when creating objects with some class variables initialized. This method may require a list of parameters, like other Ruby methods before it is defined with the DEF keyword, as follows:

Copy Code code as follows:

Class Box
def initialize (w,h)
@width, @height = W, h
End
End

Instance variables:

An instance variable is a property of a class, once we use the object created by the class object. The properties of each object are assigned separately and shared with other objects, they are accessed inside the class using the @ operator, but the public method that we use outside of the class is called the accessor method. If we put the class box defined above, then @width and @height class box instance variable.

Copy Code code as follows:

Class Box
def initialize (w,h)
# Assign Instance Avriables
@width, @height = W, h
End
End

Accessor and Setter methods:

For external access to class variables, they must define accessor methods, which are also called Getter methods. The following example shows how to use the accessor method:

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End

# Accessor methods
def printwidth
@width
End

def printheight
@height
End
End

# Create an Object
box = Box.new (10, 20)

# Use accessor methods
x = Box.printwidth ()
y = Box.printheight ()

Puts "Width of the box is: #{x}"
Puts "The Height of the box is: #{y}"


When the above code executes, it produces the following results:
Copy Code code as follows:

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

A similar access method is used to access variable values, and Ruby provides a way to set the value of these variables from the outside of the class, which is the setter method, defined as follows:
Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End

# Accessor methods
def getwidth
@width
End
def getheight
@height
End

# Setter Methods
def setwidth= (value)
@width = value
End
def setheight= (value)
@height = value
End
End

# Create an Object
box = Box.new (10, 20)

# Use setter methods
Box.setwidth = 30
Box.setheight = 50

# Use accessor methods
x = Box.getwidth ()
y = Box.getheight ()

Puts "Width of the box is: #{x}"
Puts "The Height of the box is: #{y}"


When the above code executes, it produces the following results:
Copy Code code as follows:

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

Instance method:

Also in the same way, because we define other methods using the DEF keyword, and as shown in the following illustration, only use an instance of a class, and they can be used to define the instance method. Their functionality is not limited to accessing instance variables, they can also do more things as required.

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End
# instance method
def Getarea
@width * @height
End
End

# Create an Object
box = Box.new (10, 20)

# Call Instance Methods
A = Box.getarea ()
Puts "area of the box is: #{a}"


When the above code executes, it produces the following results:
Copy Code code as follows:

Area of the box is:200

Methods and variables for the class:

A class variable is a variable, which is shared between all instances of a class. The variable is an instance of an accessible object. Two @ character class variable with prefix (@@). The class definition class variable must be initialized, as shown below.

The definition of a class method uses: Def self.methodname () ends with the end character, which is called using the Classname.methodname class name, as shown in the following example:

Copy Code code as follows:

#!/usr/bin/ruby-w

Class Box
# Initialize Our class variables
@ @count = 0
def initialize (w,h)
# Assign Instance Avriables
@width, @height = W, h

@ @count + 1
End

def self.printcount ()
Puts "Box count is: #@ @count"
End
End

# Create two Object
Box1 = Box.new (10, 20)
Box2 = box.new (30, 100)

# call class method to print box count
Box.printcount ()


When the above code executes, it produces the following results:
Copy Code code as follows:

Box Count Is:2

To_s Method:

An instance of any class defined should have a to_s method that returns a string representation of the object. The following is a simple example to represent a box object, in terms of width and height:

Copy Code code as follows:

#!/usr/bin/ruby-w

Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End
# define to_s Method
def to_s
"(w:# @width, h:# @height)" # string formatting of the object.
End
End

# Create an Object
box = Box.new (10, 20)

# to_s method is called in reference of string automatically.
Puts "String representation of Box is: #{box}"


When the above code executes, it produces the following results:
Copy Code code as follows:

String Representation of Box is: (W:10,H:20)

Access control:

Ruby provides levels of three-level protection instance methods: Public, private, and protected. Ruby does not have any access control to apply instance and class variables.

Public Methods: Anyone can be called the public method. Method defaults to public initialization, which is always the exception of private.

Private Methods:private methods cannot be accessed, or even viewed from outside the class. Only class methods can access private members.

Protected Methods: A protected method can be invoked only by defining the object of the class and its subclasses. Access is kept inside the class.

The following is a simple example to illustrate the syntax of the three access modifiers:

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End

# instance method By default it are public
def Getarea
GetWidth () * getheight
End

# define private accessor methods
def getwidth
@width
End
def getheight
@height
End
# Make them private
Private:getwidth,: GetHeight

# Instance to print area
def PrintArea
@area = getwidth () * getheight
Puts "big box area is: # @area"
End
# Make it protected
Protected:p Rintarea
End

# Create an Object
box = Box.new (10, 20)

# Call Instance Methods
A = Box.getarea ()
Puts "area of the box is: #{a}"

# try to call protected or methods
Box.printarea ()


When the above code is executed, the following results are generated. In this case, the first method is invoked successfully, but the second method gives a hint.
Copy Code code as follows:

Area of the box is:200
Test.rb:42:protected method ' PrintArea ' called for #
<box:0xb7f11280 @height =20, @width =10> (Nomethoderror)

Inheritance of classes:

One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class's project in another class, which makes it easier to create and maintain applications.

Inheritance also provides an opportunity to reuse the functionality of code and fast implementation time, but unfortunately Ruby does not support multilevel inheritance, but Ruby supports mixing. A mixin inherits multiple inheritance, and only the interface part is like a dedicated implementation.

When creating a class instead of writing a new data member and member function, the programmer can specify that the new class inherits the members of the existing class. This existing class is called a base class or a parent class and a new class is called a derived class or subclass.

Ruby also supports inheritance. Inheritance and the following examples explain this concept. The syntax of an extended class is simple. Simply add the name of a superclass declaration for a < character. For example, define a subclass of the box class Classbigbox:

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End
# instance method
def Getarea
@width * @height
End
End

# define a subclass
Class BigBox < Box

# Add a new instance method
def PrintArea
@area = @width * @height
Puts "big box area is: # @area"
End
End

# Create an Object
box = Bigbox.new (10, 20)

# Print the area
Box.printarea ()


When the above code executes, it produces the following results:
Copy Code code as follows:

Big Box Area is:200

Method Overload:

Although you can add new functions to a derived class, you sometimes want to change the behavior that is already defined in the parent class. Just by keeping the same method name and overriding the functionality of the method, as shown in the following illustration, you can do this in this example:

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End
# instance method
def Getarea
@width * @height
End
End

# define a subclass
Class BigBox < Box

# change existing Getarea as follows
def Getarea
@area = @width * @height
Puts "big box area is: # @area"
End
End

# Create an Object
box = Bigbox.new (10, 20)

# Print the area using Overriden method.
Box.getarea ()

Operator Overloading:

We want the "+" operator to use the +,* operation to multiply the width and height of a box by a scalar, here is the definition and mathematical operator of a version box class:

Copy Code code as follows:

Class Box
def initialize (w,h) # Initialize the width and height
@width, @height = W, h
End

def + (Other) # Define + to do vector addition
Box.new (@width + other.width, @height + other.height)
End

def-@ # Define unary minus to negate width and height
Box.new (-@width,-@height)
End

def * (scalar) # to perform scalar multiplication
Box.new (@width *scalar, @height *scalar)
End
End

To freeze an object:

Sometimes, we want to prevent the object from being changed. The freezing object method allows us to do this effectively by putting an object into a constant. Any object can be frozen by calling Object.freeze. Freeze object cannot be modified: its instance variable cannot be changed.

Can I use Object.frozen? Statement to check whether a given object has been frozen, the object statement method in the frozen case returns true, otherwise the value of false is returned. The following example freeze the concept:

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a class
Class Box
# constructor method
def initialize (w,h)
@width, @height = W, h
End

# Accessor methods
def getwidth
@width
End
def getheight
@height
End

# Setter Methods
def setwidth= (value)
@width = value
End
def setheight= (value)
@height = value
End
End

# Create an Object
box = Box.new (10, 20)

# Let us freez this object
Box.freeze
if (Box.frozen?)
Puts "box object is frozen Object"
Else
Puts "box object is normal object"
End

# now try the using setter methods
Box.setwidth = 30
Box.setheight = 50

# Use accessor methods
x = Box.getwidth ()
y = Box.getheight ()

Puts "Width of the box is: #{x}"
Puts "The Height of the box is: #{y}"

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

Copy Code code as follows:

Box object is frozen object
Test.rb:20:in ' setwidth= ': Can ' t modify frozen object (TypeError)
From test.rb:39

Class constants:

You can define a direct number or string value in a class without using it to define a variable as @@ 或 @. By specification, we keep the constant name in uppercase.

A constant cannot change its value once it is defined, but it can be accessed directly in the class as a constant, but if you want to access a constant outside of a class, use the class name:: Constant, as shown in the following example.

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a 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 an Object
box = Box.new (10, 20)

# Call Instance Methods
A = Box.getarea ()
Puts "area of the box is: #{a}"
Puts Box::box_company
Puts "box weight is: #{box::boxweight}"


When the above code executes, it produces the following results:
Copy Code code as follows:

Area of the box is:200
TATA INC
Box Weight Is:10

Class constant inheritance is the same as instance methods, which can be overridden.

To create an object using an assignment:

When an object is created without invoking its constructor initialization, there may be a situation where the assignment can be invoked in this case with the new method, which creates an uninitialized object, looking at the following example:

Copy Code code as follows:

#!/usr/bin/ruby-w

# define a 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 an object using new
Box1 = Box.new (10, 20)

# Create another object using allocate
Box2 = Box.allocate

# Call instance method using Box1
A = Box1.getarea ()
Puts "area of the box is: #{a}"

# Call instance method using Box2
A = Box2.getarea ()
Puts "area of the box is: #{a}"


When the above code executes, it produces the following results:
Copy Code code as follows:

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 defines executable code, this means that they are in the context of executing some object: something that must be referenced by itself. Let's take a look at what it is.

Copy Code code as follows:

#!/usr/bin/ruby-w

Class Box
# Print class Information
Puts "Type of self = #{self.type}"
Puts "Name of self = #{self.name}"
End


When the above code executes, it produces the following results:
Copy Code code as follows:

Type of self = Class
Name of self = Box

This means that a class is defined as the current object's class and executed. The method definition that the method of the Meta class and its superclass will use during execution.

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.