home PYTHONJAVA
 

Ruby Object Orientation

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

The

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

Ruby class definition

When you define a class, you actually define a blueprint for a data type. This does not actually define any data, but rather defines what the name of the class means, that is, what constitutes the object of the class, and what can be done on that object.

The class definition begins with the keyword class followed by the class name and is finally separated by a end to terminate the class definition. For example, we use the keyword class to define the Box class as follows:

class Box code end

By convention, names must begin with an uppercase letter. If you have multiple words, the first letter of each word is capitalized, but there is no separator (for example: CamelCase).

Define Ruby objects

The

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

box1 = Box.new box2= Box.new

initialize method

The

initialize method is a standard Ruby class method, a constructor for classes that works like the constructor in other object-oriented programming languages. The initialize method comes in handy when you want to initialize some class variables while creating the object. This method takes a series of arguments. As with other Ruby methods, you must place the def keyword in front of it, as follows:

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

Instance Variables

Instance variables are class properties that become properties of an object when it is created using a class. The properties of each object are assigned separately, and no values ​​are shared with other objects. Inside the class, these properties are accessed using the @ operator, and outside the class, access is done using the public method called the accessor method. Below we take the class Box defined above as an example, and @width and @height as instance variables of the class Box.

class Box def initialize(w,h) # Assigning Values ​​to Instance Variables @width, @height = w, h end end

getter & setter methods

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

Instance

#!/usr/bin/ruby -w # Define Classes class Box # Constructor def initialize(w,h) @width, @height = w, h end # Accessor Method def printWidth @width end def printHeight @height end end # Create an object to initialize the height and width of the box box = Box.new(10, 20) # Using the accessor method x = box.printWidth() y = box.printHeight() puts "Box width : #{x}" puts "Box height : #{y}"

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

Box width : 10
Box height : 20

Like the accessor methods used to access variable values, Ruby provides a way to pass arguments to a defined variable in the class outside of the class, the so-called setter method, Defined as follows:

Instance

#!/usr/bin/ruby -w # Defining 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 "Box width : #{x}" puts "Box height : #{y}"

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

Box width : 30
Box height : 50

Because two methods are very common, Ruby defines three attribute declaration methods: attr_accessor :variable_name, attr_reader :variable_name, attr_writer :variable_name . Where: accessor=reader+writer.

Also note that the variable name must be preceded by : , and the variable names should be separated by ,.

Instance method

Instance methods have the same definitions as other methods, using the def keyword, but they can only be used by class instances, as shown in the example below. . Their functionality is not limited to accessing instance variables, but can also do more of the other tasks as you need them.

Instance

#!/usr/bin/ruby -w # Defining class class Box # Construction method def initialize(w,h) @width, @height = w, h end # Construction 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 executes, it produces the following result:

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 (@@), which must be initialized in the class definition, as shown in the following example.

The

class method is defined using def self.methodname() , and the class method ends with an end delimiter. Class methods can be called using the classname.methodname form with the class name, as shown in the following example:

Instance

#!/usr/bin/ruby -w class Box # Initialize class variables @@count = 0 def initialize(w,h) # Assign value 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 the class method to output the box count Box.printCount()

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

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's a simple example of a Box object based on width and height:

Instance

#!/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)" # Define the string format of the to_s method 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 executes, it produces the following result:

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

Access Control

Ruby gives you three levels of instance method protection, public, private, or 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, methods are public, except that the initialize method is always private.
  • Private method: Private methods 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 subclasses. Access can only be done inside the class and its subclasses.

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

Instance

...
#!/usr/bin/ruby -w # Defining class class Box # Constructor method def initialize(w,h) @width, @height = w, h end # The instance method defaults to public

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

Instance

#!/usr/bin/ruby -w # Defining class class Box # Constructor method def initialize(w,h) @width, @height = w, h end # The instance method defaults to public def getArea getWidth() * getHeight end # definition private Accessor method 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 # Let the instance method be 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 calling the protected instance method box.printArea()

When the above code executes, it produces the following results. Here, the first method call succeeds, but the second method creates 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 reuse code and execute quickly. Unfortunately, Ruby does not support multiple inheritance, but Ruby supports mixins. Mixin is like a specific implementation of multiple inheritance. In multiple inheritance, only the interface part is inheritable.

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

Ruby also provides a subclassing concept, subclassing is inheritance, the following example explains this concept. Extending the syntax of a class is very simple. Just add a < character and the name of the parent class to the class statement. For example, the class defined below BigBox is a subclass of Box:

Instance

#!/usr/bin/ruby -w # Define Classes 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 executes, it produces the following result:

Big box area is : 200

Method overloading

Although you can add new features to your derived classes, sometimes you may want to change the behavior of methods that are already defined in the parent class. At this point you can leave the method name unchanged and override the function of the method, as shown in the following example:

Instance

#!/usr/bin/ruby -w # Defining class class Box # Constructor method def initialize(w,h) @width, @height = w, h end # Instance method def getArea @width * @height end end # Defining 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()

The above example runs the output as:

Big box area is : 200

operator overloading

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 negate the width and height of the Box. Below is a version of the Box class with a mathematical operator definition:

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 the unary operator - to negate the width and height Box.new(-@width, -@height) end def *(scalar) # Perform scalar multiplication Box.new(@width*scalar, @height*scalar) end end

Freeze objects

Sometimes we want to prevent objects from being changed. In the Object, the freeze method does this, and it effectively turns 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 to check if a given object has been frozen. This method will return true if the object has been frozen, otherwise it will return a false value. The following example explains this concept:

Instance

#!/usr/bin/ruby -w # Define Classes 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 # Try using Setter now... 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 executes, 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 direct numeric or string value to a variable. The definition of the constant does not require @ or @@. By convention, the name of a constant is capitalized.

Once a constant is defined, you can't change its value. You can access the constant directly inside the class, just like accessing a variable, but if you want to access constants outside of the class, you must use < b>classname::constant, as shown in the example below.

Instance

#!/usr/bin/ruby -w # Defining 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 executes, it produces the following result:

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 might be a situation where you want to create an object without calling the object constructor initialize, ie, using the new method to create the object, in which case you can call allocate. Create an uninitialized object, as shown in the following example:

Instance

#!/usr/bin/ruby -w # Define Classes 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 with new box1 = Box.new(10, 20) # Create an object with new... 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 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 is similar to Java's this, but it's quite different. Java methods are referenced in the instance method, so this is generally pointing to the current object. Ruby code is executed line by line, so self has different meanings in different contexts. Let's take a look at the following example: .

Instance

#!/usr/bin/ruby -w class Box # 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 result:

Class of self = Class
Name of self = Box

This means that the class definition can be executed by treating the class as the current object, and it also means that the method in the meta and parent classes is available during the execution of the method definition.






welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.