Further explore the concepts of classes and objects in ruby

Time:2022-5-9

RubyIs purely orientedobjectAll projects seem to be an object in ruby. Every value in ruby is an object, even the most primitive things: strings, numbers, and even true and false. Even oneclassItself is an object, which is an instance of class. This chapter will cover Ruby’s object orientation through all functions.

Class is used to specify the form of objects. It combines data representation and methods to manipulate these data and convert them into a neat package. The data and methods in a class are called class members.
Definition of ruby class:

Define a class that defines the data type of the sketch. 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 is separated from the keyword class, class name and end. For example, we define the box class and use the class keyword as follows:

class Box
   code
end

The name must start with a capital letter. According to the Convention, the name contains multiple words, and each word is executed together without a separator (hump).
Define Ruby objects:

Class is the blueprint of object, so it is basically created from a class object. We declare a class object using the new keyword. The following statement declares two objects, box class:

?
1
2
box1 = Box.new
box2 = Box.new

Initialize method:

The initialize method is a standard Ruby class method, as well as other object-oriented methodsprograming languageThe construction method of works in the same way. The initialize method is useful. When creating an object, some class variables are initialized. This method may require a list of parameters. Like other Ruby methods, it is defined with the def keyword, as shown below:

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

Instance variable:

Instance variable is an attribute of a class. Once the class object we use is created, it is the attribute of the object. The properties of each object are assigned separately and shared with other objects. They are accessed using the @ operator inside the class, but the public methods we use outside the class are called accessor methods. If we put the above defined class box, then the @ width and @ height class box instance variables.

?
1
2
3
4
5
6
class Box
  def initialize(w,h)
   # assign instance avriables
   @width, @height = w, h
  end
end

Accessor and setter methods:

In order to access the variables of the class externally, they must define accessor methods, which are also called getter methods. The following example demonstrates how to use the accessor method:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/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:

?
1
2
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??, It is defined as follows:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/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:

?
1
2
Width of the box is : 30
Height of the box is : 50

Example method:

In the same way, because we use the def keyword to define other methods, and as shown in the figure below, only instances of one class can be used to define the instance method. Their functions are not limited to accessing instance variables, but they can also do more as required.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/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:

?
1
Area of the box is : 200

Methods and variables of class:

A class variable is a variable that is shared among all instances of a class. This variable is an instance, which is an instance of an accessible object. Two @ character class variables are prefixed (@ @). Class variables defined in a class must be initialized, as shown below.

Method defined by class: self. Def Methodname() ends with the end character and will be called using classname Methodname class name, as shown in the following example:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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:

?
1
Box count is : 2

to_ S method:

An instance of any class defined should have a to_ The s method returns a string representation of the object. The following is a simple example to represent a box object in terms of width and height:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/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:

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

Access control:

Ruby provides three levels of protection for instance methods: public, private and protected. Ruby does not have any access control over application instances and class variables.

  1. Public methods: anyone can be called a public method. Method defaults to public initialization, except that this is always 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 only by defining objects of the class and its subclasses. Access is saved inside the class.

The following is a simple example to illustrate the syntax of the three access modifiers:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/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 hint.

?
1
2
3
Area of the box is : 200
test.rb:42: protected method `printArea' called for #
<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)

Class inheritance:

One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define projects in one class in another, which makes it easier to create and maintain applications.

Inheritance also provides an opportunity to reuse code functions and fast implementation time, but unfortunately Ruby does not support multi-level inheritance, but Ruby supports blending. 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, programmers can specify that the new class inherits the members of the existing class. This existing class is called the base class or parent class, and the new class is called the derived class or child class.

Ruby also supports inheritance. Inheritance and the following examples illustrate this concept. The syntax of extension classes is simple. Just add the name of the super class declaration with a < character. For example, define the subclass classbigbox of the box class:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/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:

?
1
Big box area is : 200

Method overload:

Although you can add new functions to derived classes, sometimes you want to change the behavior of methods that are already defined in the parent class. Just keep the same method name and rewrite the function of the method, as shown in the figure below. In this example, you can do this:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/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 overloading:

We want the “+” operator to use +, * to multiply the width and height of a box by a scalar. Here is the definition and mathematical operator of a version of box class:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 [email protected]        # 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

Frozen object:

Sometimes, we need to prevent the changed object. The method of freezing objects allows us to do this, effectively turning an object into a constant. Any object can be frozen by calling object freeze。 Frozen objects cannot be modified: its instance variables cannot be changed.

You can use object frozen? Statement to check whether a given object has been frozen. The object statement method in the case of freezing returns true, otherwise it returns false. The following is an example of the concept of free:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/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:

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

Class constant:

Instead of defining a variable as @ @ or @, you can assign a direct numeric or string value to a class definition. According to the specification, we keep constant names capitalized.

Once a constant is defined, it cannot change its value, but it can be accessed directly in the class like a constant. However, if you want to access a constant outside the class, you should use the class name:: constant, as shown in the following example.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/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:

?
1
2
3
Area of the box is : 200
TATA Inc
Box weight is: 10

Class constant inheritance, like instance methods, can be overridden.
Create object usage assignment:

When an object is created without calling its constructor for initialization, there may be a case: the new method is adopted, in which case the allocation can be called, which will create an uninitialized object. See the following example:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/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:

?
1
2
3
4
5
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 classes define executable code, this means that they have some objects in the context of execution: things that must be referenced by themselves. Let’s see what it is.

?
1
2
3
4
5
6
7
#!/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:

?
1
2
Type of self = Class
Name of self = Box

This means that a class is defined as the class of the current object and executed. The methods in the metaclass and its superclass will be defined by the methods used during execution.

Recommended Today

Android 12 (s) multimedia learning (IX) mediacodec

In this section, learn the working principle of mediacodec and the relevant code path: http://aospxref.com/android-12.0.0_r3/xref/frameworks/av/media/libstagefright/MediaCodec.cpp   1. Create mediacodec object Mediacodec provides two static methods for creating mediacodec objects: createbytype and createbycomponentname. Let’s take a look at them respectively CreateByTypeThe parameter of the method needs to give a mimeType and specify whether it is an […]