Further dive into the class and object concepts in Ruby and the concept of ruby objects

Source: Internet
Author: User

Further dive into the class and object concepts in Ruby and the concept of ruby objects

Ruby is a pure object-oriented language, and all projects seem to need Ruby as an object. Every value in Ruby is an object, even the most primitive: String, number or even true or false. Even if a Class is an object, it is an instance of the Class. This chapter covers Ruby object-oriented through all functions.

Class is used to specify the form of the object. It combines the data representation and method to manipulate the data and convert it into a neat package. In a class, data and methods are called class members.
Ruby class definition:

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

The class definition start is separated from the class name and end of the keyword. For example, we define the Box class to use the class keyword as follows:

Class Box
Code
End

The name must start with an uppercase letter and contain multiple words according to the Conventions. Each word has no separator (camper.
Define Ruby objects:

Class is the blueprint of the object, so it is basically a class object created from. We declare that the object of a class uses 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 language constructor methods. The initialize method is useful. Some class variables are initialized when an object is created. This method may require a list of parameters. It is defined by the def keyword like other methods earlier than Ruby, as shown below:

Class Box
Def initialize (w, h)
@ Width, @ height = w, h
End
End

Instance variables:

An instance variable is a type of attribute of a class. Once the class object we use is created, the attributes of the object. The attributes of each object are assigned values and shared with other objects. They are accessed using the @ operator within the class, but the public methods we use outside the class are called accessors. If we put the Box class defined above, then @ width and @ height class Box instance variables.

class Box
  def initialize(w,h)
   # assign instance avriables
   @width, @height = w, h
  end
end

Accessors and setter methods:

To enable external variables, they must define accessors. These accessors are also called getter methods. The following example demonstrates how to use the accessors:

#!/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 "Height of the box is : #{y}"

When the above code is executed, it will produce the following results:

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

Similar access methods are used to access variable values. Ruby provides a method to set the values of these variables from outside the class, that is, the setter method ??, Definition:

#!/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 "Height of the box is : #{y}"

When the above code is executed, it will produce the following results:

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

Instance method:

In the same way, because we use the def keyword to define other methods and use only the instances of one class as shown in, they can be used to define this instance method. Their functions are not limited to accessing instance variables. They can also do more 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
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 is executed, it will produce the following results:

Area of the box is : 200

Class methods and variables:

A class variable is a variable, which is shared among all instances of a class. This variable is an instance that can access the object instance. Two @ character class variables have a prefix (@@). Class variables must be initialized as follows.

Use def self. methodname () to end with the end character. It is called the class name using classname. methodname, 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 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 is executed, it will produce the following results:

Box count is : 2

To_s method:

The instance of any class defined should have a to_s method to return a string to represent the object. The following uses 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
end

# create an object
box = Box.new(10, 20)

# to_s method will be called in reference of string automatically.
puts "String representation of box is : #{box}"

When the above code is executed, it will produce the following results:

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

Access control:

Ruby provides three levels of instance protection methods: public, private, and protected. Ruby has no access control over application instances and class variables.

  1. Public Methods: Anyone can be called a public method. The method is public initialization by default, except for private. .
  2. Private Methods: private Methods cannot be accessed, or even browsed from outside the class. Only class methods can access private members.
  3. Protected Methods: Protected Methods can be called. You can only define objects of classes and their subclasses. The access is saved in 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 is 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 :printArea
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. Here, the first method is called successfully, but the second method gives a prompt.

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 in another class project, which makes it easier to create and maintain applications.

Inheritance also provides an opportunity to reuse code functions and fast implementation time. Unfortunately, Ruby does not support multi-level inheritance, but Ruby supports mixing. A mixin inherits multiple inheritance, and only the Interface part is like a special implementation.

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

Ruby also supports inheritance. This concept is inherited and explained in the following example. The syntax of the extension class is very simple. You only need to add the name of the <character's superclass declaration. For example, define the subclass classBigBox of the Box class:

#!/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 is executed, it will produce the following results:

Big box area is : 200

Method overload:

Although a new function can be added to a derived class, sometimes the behavior you want to change has been defined in the parent class. You only need to maintain the same method name and override the function of this method, as shown in the following example:

#!/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 method 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 overload:

We want the "+" operator to use +. * The operation is multiplied by a scalar by the width and height of a Box. Here is the definition and mathematical operator of a Box class:

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

Freeze object:

Sometimes, we need to prevent objects from being changed. The method of freezing objects allows us to achieve this, effectively putting an object to a constant. Any Object can be frozen by calling Object. freeze. Do not modify frozen objects: Do not change its instance variables.

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

#!/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 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 "Height of the box is : #{y}"

When the above code is executed, it will produce the following results:

Box object is frozen object
test.rb:20:in `setWidth=': can't modify frozen object (TypeError)
    from test.rb:39

Class constant:

You can assign a direct number or string value in the class definition, instead of defining a variable as @ or @. According to the specification, we keep constant name writing.

Once defined, a constant cannot change its value, but it can be directly accessed in the class like a constant. However, if you want to access a constant outside of the class, you must 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 = 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 is executed, it will produce the following results:

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

The class constant inheritance is the same as the instance method and can be overwritten.
Use allocation to create objects:

When you create an object without calling its constructor initialization, there may be a situation where the new method is used, in which case the allocation can be called, this creates an uninitialized object. See 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
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 is executed, it will produce the following results:

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 have some objects in the context of execution: they must all reference things. Let's see what it is.

#!/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 is executed, it will produce the following results:

Type of self = ClassName of self = Box

This means that a class is defined and executed as the class of the current object. The method definition used during the execution of the metachiname and its superclasses.


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.