A basic tutorial on object-oriented programming for Ruby _ruby topics

Source: Internet
Author: User
Tags class definition constant inheritance instance method scalar string format

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 thing: strings, numbers, and even true and false are objects. The class itself is also an object and is an instance of class. This chapter will show you all the key features associated with Ruby-oriented objects.

Class is used to specify the form of an object, combining data representations 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 are actually defining a blueprint for a data type. This actually does not define any data, but rather defines what the name of the class means, that is, what the object of the class is defined by, and what action can be performed on the object.

The class definition begins with the keyword class, followed by the class name, and finally separated by an 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 start with uppercase letters, and if they contain more than one word, each word is capitalized, but there are no delimiters (for example: CamelCase).
Define Ruby Objects

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

Box1 = box.new
Box2 = box.new

Initialize method

The Initialize method is a standard Ruby-class approach, similar to the constructor working principle in other object-oriented programming languages. The Initialize method comes in handy when you want to initialize some class variables while creating objects. This method takes a series of arguments, and like 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

Instance variables

Instance variables are class properties that become properties of objects when they are created using a class. The properties of each object are assigned separately, and values are not shared between the other objects. Inside the class, these properties are accessed using the @ operator, and outside the class, by using a public method called the accessor method. Here we take @width and @height as instance variables for class box, using the class box defined above.

Class Box
  def initialize (w,h)
   # Assigns value to instance variable
   @width, @height = W, h
  end

Accessor & Setup Methods

In order to use variables outside of the class, we must define these variables within the accessor method, which is also called the accessor method. The following example demonstrates the use of accessor methods:

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h end
 
  # Accessor method
  def printwidth
   @width end
 
  def printheight @height end
 
# Create objects
box = box.new
 
# using accessor method
x = Box.printwidth ()
y = box.printheight ()
 
puts "Width of the" Bo X is: #{x} "
puts" Height of the box is: #{y} "

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

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

Like accessor methods for accessing variable values, Ruby provides a way to set variable values outside of a class, known as a setup method, defined as follows:

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h end
 
  # Accessor method
  def getwidth
   @width end
  def getheight
   @height end
 
  # set method
  def setwidth = (value)
   @width = value
  end
  def setheight= (value)
   @height = value
  end
 
# Create Object
box = box.new (
 
m) # using the Setup method
box.setwidth =
box.setheight =
 
# Use accessor method
x = Box.get Width ()
y = box.getheight ()
 
puts "width of the box is: #{x}"
puts "Height of the Box": #{y} "

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

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

Instance method

Instance methods are defined as other methods, using the DEF keyword, but they can only be used through class instances, as shown in the following example. Their functionality is not limited to accessing instance variables, but can also do more to your needs.

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h< C6/>end
  # instance method
  def getarea
   @width * @height
  end
 
# Create object
box = Box.new (a)
 
# Invoke 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:2
Classes of Methods & class variables

are variables that are shared among 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 (@@), and class variables must be initialized in the class definition, as shown in the following example.

The class method uses the Def self.methodname () definition, and the class method ends with the end delimiter. Class methods can be invoked using a classname.methodname form with a class name, as shown in the following example:
#!/usr/bin/ruby-w class
 
Box
  # Initializes the classes variable
  @ @count = 0
  def initialize (w,h)
   # Assign value to instance variable
   @width, @height = W, h
 
   @ @count + + 1 End
 
  def Self.printcount ()
   puts ' box count is: #@ @count '
  end
 
# to create two objects
Box1 = Box.new (a)
Box2 = Box.new (M)
 
# Invokes the class method to output the box Count
Box.printcount ()

When the above code executes, it produces 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 an object. The following is a simple example that represents a 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 to_s method C8/>def to_s
   "(w:# @width, h:# @height)" # object string format end
 
# Create object
box = Box.new (a)
 
# Automatic call to to_s method
puts "String representation of Box is: #{box}"

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

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

Access control

Ruby provides you with three levels of instance method protection, public, private, or protected, respectively. Ruby does not apply any access control on instance and class variables.

    • Public method: The public method can be invoked 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 invoked by objects of the class and its subclasses. Access can also be performed only within a class and its subclasses.

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

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h end
 
  # instance method defaults to public
  def Getarea
   getwidth () * GetHeight end
 
  # defines private accessor methods
  def getwidth
   @ Width
  end
  def getheight
   @height
  ' # make them private
  private:getwidth: getheight
 
  # instance methods for output areas
  def printarea
   @area = getwidth () * getheight
   puts "big box area is: # @area"
  end
   # Let instance method be protected
  protected:p Rintarea end
 
# Create object
box = Box.new (Ten)
 
# Call instance method
a = Box.getarea ()
puts "area of the box is: #{a}"
 
# attempts to invoke an instance method of protected
Box.printarea ()

When the above code executes, it produces the following results. In this case, 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, @w Idth=10> (Nomethoderror)

Inheritance of Classes

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 to reuse code and execute quickly, and unfortunately Ruby does not support multiple inheritance, but Ruby supports Mixins. Mixin is like a specific implementation of multiple inheritance, in which only the interface part is inheritable.

When you create a class, the programmer can directly specify that the new class inherits from a member of an existing class, so that you do not have to write new data members and member functions from scratch. This existing class is called a base class or a parent class, and the new class is called a derived class or subclass.

Ruby also provides a subclass of the concept of subclass is inherited, the following example explains this concept. The syntax for extending a class is simple. Just add a < character and the name of the parent class to the class statement. For example, the following defines the class BigBox as a subclass of Box:

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h end
  # Instance method
  def getarea
   @width * @height
  end
 
# define subclasses class
BigBox < Box
 
  # Add a new instance method C15/>def printarea
   @area = @width * @height
   puts "big box: # @area ' End
 
# Create object
b Ox = bigbox.new (m)
 
# Output Area
Box.printarea ()

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

Big Box Area is:200

Method overload

Although you can add new features to a derived class, sometimes you might want to change the behavior of methods already defined in the parent class. You can then keep the method name unchanged and overload the method's functionality, as shown in the following example:

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h end
  # Instance method
  def getarea
   @width * @height
  end
 
# defines subclasses class
BigBox < Box
 
  # changing existing Getarea Method
  def getarea
   @area = @width * @height
   puts "big box area is: # @area '
  end
 
# Create Object
box = bigbox.new
 
# Use overloaded method to output area
Box.getarea ()

Operator overloading

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

Class Box
 def initialize (w,h) # initializes the width and height
  @width, @height = W, h
 end
 
 def + (other)     # definition + to execute vectors Addition
  box.new (@width + other.width, @height + other.height)
 end
 
 def-@        # defines a unary operator-to reverse
  width and height Box.new (-@width,-@height)
 End
 
 def * (scalar)    # performs scalar multiplication
  box.new (@width *scalar, @height *scalar) End End

Freezing objects

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

Can you use Object.frozen? method to check whether a given object has been frozen. If the object is frozen, the method returns True, otherwise a false value is returned. The following example explains this concept:

#!/usr/bin/ruby-w
 
# defines class class
Box
  # constructor Method
  def initialize (w,h)
   @width, @height = W, h end
 
  # Accessor method
  def getwidth
   @width end
  def getheight
   @height end
 
  # set method
  def setwidth = (value)
   @width = value
  end
  def setheight= (value)
   @height = value
  end
 
# Create Object
box = box.new
 
# 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 Setup method
Box . SetWidth =
box.setheight =
 
# Use accessor method
x = Box.getwidth ()
y = box.getheight ()
 
puts "Width o f The box is: #{x} "
puts" the Height of the box is: #{y} "

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

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 within a class by assigning a direct numeric or string value to a variable, and the definition of a constant does not require the use of @ or @@. By convention, the name of a constant uses uppercase.

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

#!/usr/bin/ruby-w
 
# definition class
Box
  box_company = "TATA Inc"
  boxweight = Ten
  # constructor method
  def Initialize (w,h)
   @width, @height = W, h
  End
  # instance method
  def getarea
   @width * @height
End
 
# Create object
box = box.new
 
# Invoke instance method
A = Box.getarea ()
puts "area of the box is: #{a}"
Pu TS Box::box_company
puts "box weight is: #{box::boxweight}"

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

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

Class constants can be inherited, and can be overloaded like instance methods.
creating objects using allocate

There may be a situation where you want to create an object without invoking the object Builder initialize, that is, by using the new method to create an object, in which case you can call allocate to create an uninitialized object, as shown in the following example:

#!/usr/bin/ruby-w
 
# defines 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
 
# Create objects using new 
   
    box1 = Box.new (M)
 
# Use Allocate to create 21 objects
Box2 = box.allocate
 
# Use Box1 to invoke instance method
A = Box1.getarea () C19/>puts "The" of the box is: #{a} "
 
# use Box2 to invoke instance method
A = Box2.getarea () puts" area of the
box is: #{a} "

   

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

Area of the box is:200
test.rb:14:warning:instance variable @width not initialized
Test.rb:14:warning:inst ance 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, which means that they can be executed in the context of an object, self must refer to something. Let's take a look at the following example:.

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

Type of self = Class
Name of self = Box

This means that a class definition can be executed by taking the class as the current object, and also means that the method in the class and the 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.