Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby Object-Oriented

Ruby Object-Oriented

Ruby is a pure object-oriented language, and everything in Ruby appears in the form of an object. Every value in Ruby is an object, even the most primitive things: strings, numbers, and even true and false are objects. The class itself is also aobject, and is Class an instance of the class. This chapter will explain all the major features related to Ruby object orientation.

A class is used to specify the form of an object. It combines data representation and methods, organizing data into a neat package. The data and methods in a class are called the 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 defines what the name of the class means; that is, it defines what the objects of the class will consist of and what operations can be performed on them.

A class definition begins with the keyword class followed bythe class name, and finally ends with a end to delimit and terminate the class definition. For example, we use the keyword class to define the Box class, as follows:

class

Box

code

end

By convention, the name must begin with an uppercase letter. If it contains multiple words, the first letter of each word is capitalized, with no separators between them (for example: CamelCase).

Defining Ruby Objects

A class provides the blueprint for an object, so basically, objects are created from a class. We use the new keyword to declare an object of a class. The following statement declares two objects of the Box class:

box1

=

Box

.

new

box2

=

Box

.

new

The initialize Method

initialize method is a standard Ruby class method and is the constructor of the class, similar to the constructor in other object-oriented programming languages. The initialize method is useful when you want to initialize some class variables while creating an object. This method takes a series of parameters. As with other Ruby methods, when using it you must place the def keyword before it, as shown below:

class

Box

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

end

Instance Variables

Instance Variablesare class attributes, which become attributes of the object when an object is created from the class. Each object's attributes are assigned individually and values are not shared with other objects. Inside the class, these attributes are accessed using the @ operator; outside the class, they are accessed using what are calledaccessor methods'spublicmethods. Below we take the class defined above Box as an example and treat @width and @height as instance variables of the Box class.

class

Box

def

initialize

(

w

,

h

)

Assigning values to instance variables

@width

,

@height

=

w

,

h

end

end

Accessor (getter) & Setter Methods

To read variables defined in a class from outside the class, we can define accessor (getter) methods. The following example demonstrates the use of accessor methods:

Example

!/usr/bin/ruby -w

Define a class

class

Box

constructor

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

accessor methods

def

printWidth

@width

end

def

printHeight

@height

end

end

Create an object, initializing the box's height and width

box

=

Box

.

new

(

10

,

20

)

Using accessor methods

x

=

box

.

printWidth

(

)

y

=

box

.

printHeight

(

)

puts

"

Box width : #{x}

"

puts

"

Box height : #{y}

"

Try it »

When the above code is executed, it produces the following result:


盒子宽度 : 10
盒子高度 : 20

Similar to accessor methods used to read variable values, Ruby provides a way to pass arguments into variables defined in a class from outside the class, known assetter methods, defined as follows:

Example

!/usr/bin/ruby -w

Define a class

class

Box

Constructor methods

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

Creating objects

box

=

Box

.

new

(

10

,

20

)

Using setter methods

box

.

setWidth

=

30

box

.

setHeight

=

50

Using accessor methods

x

=

box

.

getWidth

(

)

y

=

box

.

getHeight

(

)

puts

"

Box width : #{x}

"

puts

"

Box height : #{y}

"

Try it »

When the above code is executed, it produces the following result:


盒子宽度 : 30
盒子高度 : 50

Since these two methods are very commonly used, Ruby defines attr_accessor :variable_name、attr_reader :variable_name、attr_writer :variable_name three attribute declaration methods. Among them:accessor=reader+writer。

Also note: a variable name must be prefixed with : , and variable names must be separated by , .

Instance Methods

Instance Methodsis defined in the same way as other methods, using the def keyword, but they can only be used through a class instance, as shown in the example below. Their functionality is not limited to accessing instance variables; they can also perform many other tasks as you require.

Example

!/usr/bin/ruby -w

Define a class

class

Box

Constructor

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Instance Methods

def

getArea

@width

@height

end

end

Creating objects

box

=

Box

.

new

(

10

,

20

)

Calling instance methods

a

=

box

.

getArea

(

)

puts

"

Area of the box is : #{a}

"

Try it »

When the above code is executed, it produces the following result:


Area of the box is : 200

Class Methods & Class Variables

Class variableare variables shared among all instances of a class. In other words, an instance of a class variable can be accessed by all object instances. Class variables are prefixed with two @ characters (@@), and must be initialized within the class definition, as shown in the example below.

Class MethodsUse def self.methodname() definition; class methods end with the end delimiter. A class method can be called using the form with the class name classname.methodname prefix, as shown in the example below:

Example

!/usr/bin/ruby -w

class

Box

Initializing class variables

@@count

=

0

def

initialize

(

w

,

h

)

Assigning 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

)

Calling a class method to output the box count

Box

.

printCount

(

)

Try it »

When the above code is executed, it produces the following result:


Box count is : 2

The to_s Method

Any class you define has an to_s instance method that returns a string representation of the object. The following is a simple example representing a Box object in terms of width and height:

Example

!/usr/bin/ruby -w

class

Box

Constructor methods

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Defining the to_s method

def

to_s

"

(w:#@width,h:#@height)

"

String format of the object

end

end

Creating objects

box

=

Box

.

new

(

10

,

20

)

Automatically calling the to_s method

puts

"

String representation of box is : #{box}

"

Try it »

When the above code is executed, it produces the following result:


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

Access Control

Ruby provides you with three levels of protection for instance methods, namely public, private, or protected. Ruby does not apply any access control to instance and class variables.

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

Example

!/usr/bin/ruby -w

Define a class

class

Box

Constructor methods

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Instance methods are public by default

def

getArea

getWidth

(

)

getHeight

end

Defining private accessor methods

def

getWidth

@width

end

def

getHeight

@height

end

make them private

private

:

getWidth

, :

getHeight

Instance method used to output the area

def

printArea

@area

=

getWidth

(

)

getHeight

puts

"

Big box area is : #@area

"

end

Making the instance method protected

protected

:

printArea

end

Creating objects

box

=

Box

.

new

(

10

,

20

)

Calling instance methods

a

=

box

.

getArea

(

)

puts

"

Area of the box is : #{a}

"

Trying to call a protected instance method

box

.

printArea

(

)

Try it »

When the above code is executed, it produces the following result. Here, the first method call succeeds, but the second method causes a problem.


Area of the box is : 200
test.rb:42: protected method `printArea' called for #
 (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, making it easier to create and maintain applications.

Inheritance helps with code reuse and fast execution. Unfortunately, Ruby does not support multiple inheritance, but Ruby supports mixins. A mixin is like a specific implementation of multiple inheritance in which only the interface portion is inheritable.

When creating a class, a programmer can directly specify that the new class inherits from the members of an existing class, so there is no need to write new data members and member functions from scratch. This existing class is called thebase class or superclass, and the new class is called thederived class or subclass。

Ruby also provides the concept of subclassing, which is inheritance. The following example explains this concept. 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 following defines a subclass of class BigBox Is Box :

Example

!/usr/bin/ruby -w

Define a class

class

Box

Constructor methods

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Instance Methods

def

getArea

@width

@height

end

end

Define the subclass

class

BigBox

<

Box

Adding a new instance method

def

printArea

@area

=

@width

@height

puts

"

Big box area is : #@area

"

end

end

Creating objects

box

=

BigBox

.

new

(

10

,

20

)

Outputting the area

box

.

printArea

(

)

Try it »

When the above code is executed, it produces the following result:


Big box area is : 200

Method overloading

Although you can add new functionality to a derived class, sometimes you may want to change the behavior of a method already defined in the parent class. In this case, you can keep the method name unchanged and simply override the method's functionality, as shown in the example below:

Example

!/usr/bin/ruby -w

Define a class

class

Box

Constructor methods

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Instance Methods

def

getArea

@width

@height

end

end

Define the subclass

class

BigBox

<

Box

Changing the existing getArea method

def

getArea

@area

=

@width

@height

puts

"

Big box area is : #@area

"

end

end

Creating objects

box

=

BigBox

.

new

(

10

,

20

)

Using the overridden method to output the area

box

.

getArea

(

)

Try it »

The above example produces the following output:


Big box area is : 200

operator overloading

We want to use the + operator to perform vector addition of two Box objects, the * operator to multiply the width and height of a Box, and the unary - operator to negate the width and height of a Box. The following is a version of the Box class with mathematical operator definitions:

class

Box

def

initialize

(

w

,

h

)

Initializing width and height

@width

,

@height

=

w

,

h

end

def

(

other

)

Defining + to perform vector addition

Box

.

new

(

@width

other

.

width

,

@height

other

.

height

)

end

def

-@

Defining the unary operator - to negate width and height

Box

.

new

(

@width

, -

@height

)

end

def

(

scalar

)

Performing scalar multiplication

Box

.

new

(

@width

scalar

,

@height

scalar

)

end

end

Freezing Objects

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

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

Example

!/usr/bin/ruby -w

Define a class

class

Box

Constructor methods

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

Creating objects

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 using the setter method

box

.

setWidth

=

30

box

.

setHeight

=

50

Using accessor methods

x

=

box

.

getWidth

(

)

y

=

box

.

getHeight

(

)

puts

"

Width of the box is : #{x}

"

puts

"

Height of the box is : #{y}

"

Try it »

When the above code is executed, it produces the following result:


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 constant inside a class by assigning a literal numeric or string value to a variable. Constants do not need to be defined using @ or @@. By convention, constant names use uppercase letters.

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

Example

!/usr/bin/ruby -w

Define a class

class

Box

BOX_COMPANY

=

"

TATA Inc

"

BOXWEIGHT

=

10

Constructor methods

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Instance Methods

def

getArea

@width

@height

end

end

Creating objects

box

=

Box

.

new

(

10

,

20

)

Calling instance methods

a

=

box

.

getArea

(

)

puts

"

Area of the box is : #{a}

"

puts

Box

::

BOX_COMPANY

puts

"

Box weight is: #{Box::BOXWEIGHT}

"

Try it »

When the above code is executed, it produces the following result:


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

Class constants can be inherited and can also be overridden like instance methods.

Creating Objects with allocate

There may be a situation where you want to create an object without calling the object's constructor initialize , that is, creating an object using the new method. In this case, you can call allocate to create an uninitialized object, as shown in the example below:

Example

!/usr/bin/ruby -w

Define a class

class

Box

attr_accessor

:

width

, :

height

Constructor methods

def

initialize

(

w

,

h

)

@width

,

@height

=

w

,

h

end

Instance Methods

def

getArea

@width

@height

end

end

Creating an object with new

box1

=

Box

.

new

(

10

,

20

)

Creating another object with allocate

box2

=

Box

.

allocate

Calling an instance method with box1

a

=

box1

.

getArea

(

)

puts

"

Area of the box is : #{a}

"

Calling an instance method with box2

a

=

box2

.

getArea

(

)

puts

"

Area of the box is : #{a}

"

Try it »

When the above code is executed, it produces the following result:


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 some similarities but are quite different. Java methods are all referenced in instance methods, so this generally points to the current object. Ruby code is executed line by line, so self has different meanings in different contexts. Let's look at the following example: .

Example

!/usr/bin/ruby -w

class

Box

Outputting class information

puts

"

Class of self = #{self.class}

"

puts

"

Name of self = #{self.name}

"

end

Try it »

When the above code is executed, it produces the following result:


Class of self = Class
Name of self = Box

This means the class definition is executed by treating the class as the current object, and also means that methods in the metaclass and superclass are available during the execution of the method definition.