Further delve into the class and object concepts in Ruby _ruby topics

Source: Internet
Author: User
Tags class definition constructor inheritance 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:

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:

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:

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.

Class Box
  def initialize (w,h)
   # Assign Instance avriables
   @width, @height = W, h
  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:

#!/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

-# Create an object
box = Box.new (M) # use

accessor methods
x = Box.printwidth ()
y = box.printheight ()

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: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:

#!/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

  # setters Methods
  def setwidth= (value)
   @width = value
  end
  def setheight= (value)
   @height = value
  end

# Create an object
box = box.new (M)

# Use setter methods
   
    box.setwidth =
box.setheight = m use

accessor methods
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 results:

The 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.

#!/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

# Create a objec t
box = box.new

# Call instance methods
A = Box.getarea () puts ' area of the
' box is: #{a} '

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

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:

#!/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 co UNT is: #@ @count '
  end

# Create two object
Box1 = Box.new (a) Box2 = Box.new
(m) 
   # Call class method to print box Count
box.printcount ()

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

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:

#!/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

-# Create an object
box = Box.new (M) # to_s method would be

called in reference of string a utomatically.
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 levels of three-level protection instance methods: Public, private, and protected. Ruby does not have any access control to apply instance and class variables.

    1. Public Methods: Anyone can be called the public method. Method defaults to public initialization, which is always the exception of private.
    2. Private Methods:private methods cannot be accessed, or even viewed from outside the class. Only class methods can access private members.
    3. 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:

#!/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 method to print area
  def printarea
   
     @area = GetWidth () * getheight
   puts "big box area is: # @area '
  end
  # make it protected
  protected:p RI Ntarea
End

# Create an object
box = Box.new (M) # call

instance methods
A = Box.getarea () 
    puts "Area of the box are: #{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.

Area of the box is:200
test.rb:42:protected method ' PrintArea ' called for #
<box:0xb7f11280 @height =20, @wid Th=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:

#!/usr/bin/ruby-w

# define a class
class Box
  # constructor Method
  def initialize (w,h)
   @width, @ Height = W, h
  End
  # instance to
  def getarea
   @width * @height
  end

# define a SUBCLA SS
Class BigBox < Box

  # Add a new instance method
  def printarea
   @area = @width * @height
   puts "Big Box area is: # @area '
  end
# ' Create an

object
box = bigbox.new (M)

# Print the 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 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:

#!/usr/bin/ruby-w

# define a class
class Box
  # constructor Method
  def initialize (w,h)
   @width, @ Height = W, h
  End
  # instance to
  def getarea
   @width * @height
  end

# define a SUBCLA SS
Class BigBox < Box

  # Change existing Getarea method as follows
  def getarea
   @area = @width * @hei Ght
   puts "big box area are: # @area" End end

# Create an object
box = bigbox.new (M)

# PR int 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:

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

 def + (Other) 
   
    # Define + to does vector addition
  box.new (@width + other.width, @height + other.height)
 end

 def-@        # Defin E unary minus to negate width and height
  box.new (-@width,-@height)
 End

 def * (scalar)    # to perform SCA Lar multiplication
  box.new (@width *scalar, @height *scalar)
 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:

#!/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

  # setters Methods
  def setwidth= (value)
   @width = value
  end
  def setheight= (value)
   @height = value
  end

# Create an object
box = box.new (M)

# 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 using setter Methods
Box.setwidth =
box.setheight = m use

accessor methods
x = Box.getwidth ()
y = box.g Etheight ()

puts "Width of the box is: #{x}"
puts "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 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.

#!/usr/bin/ruby-w

# define a class
class Box
  box_company = "TATA Inc"
  boxweight =
  # constructor Me Thod
  def initialize (w,h)
   @width, @height = W, h
  End
  # instance method
  def getarea
   @width * The height end

# Create an object
box = Box.new (M) # call

instance methods
A = Box.get Area ()
puts ' area of ' box is: #{a} '
puts 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 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:

#!/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

-# Create an object using new
Box1 = Box.new (a)

# Create another object using ALLOCATE
   box2 = box.allocate

# Call instance method using Box1
a = Box1.getarea ()
puts ' area of ' 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:

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 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.

#!/usr/bin/ruby-w

class Box
  # Print class information
  puts ' Type of self = #{self.type} '
  puts ' Name of SE LF = #{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 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.