Latest web development tutorials

Ruby object-oriented

Ruby is a pure object-oriented language, Ruby, everything is in the form of objects. Each value in Ruby is an object, even the most primitive thing: strings, numbers, and even true and false are objects. The class itself is anobject thatis an instanceof classClass. This chapter tells you explain all the major functions associated with the Ruby object-oriented.

Class is used to form the specified object, which combines data representation and methods to organize data into a neat package. Class data and methods are called members of the class.

Ruby class definition

When you define a class, you actually define a blueprint for a data type. This actually does not define any data, but the definition of what the name of the class means, that is to say, the definition of what constitutes an object of class will be, and what actions can be performed on the object.

Class definition begins with the keywordclass, followed by the class name,and finallyendwith a separated representation curtail such definitions. For example, we use the class keyword to define the Box class, as follows:

class Box
   code
end

By convention, the name must begin with a capital letter, if it contains more than one word, capitalize the first letter of each word, but here is no delimiter (for example: CamelCase).

Ruby object definitions

Class provides the blueprint for an object, so basically, the object is created in accordance with the class. We use thenew keyword to declare the class object.The following statement declares the class Box two objects:

box1 = Box.new
box2 = Box.new

initialize method

initialize method is a standard Ruby class method is the constructor of the class, similar to other object-oriented programming languages constructorworks. When you want to initialize some variables in the class to create an object at the same time, initialize method comes in handy. The method takes a series of arguments, like other Ruby methods, using this method, it must be placed in front ofthe def keyword, as follows:

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

Instance variables

Property classinstance variables is that they create when using the class object will become property of the object.Individual properties of each object is assigned, among other objects, and do not share values. Within the class is to use the @ operator to access those properties outside the class, it iscommon to use a method called accessor methodsof access. Here we define the classBox above as an example, the class Box @width and @height as instance variables.

class Box
   def initialize(w,h)
      # 给实例变量赋值
      @width, @height = w, h
   end
end

Accessors (accessor) & setter (setter) method

In order to use external variables of the class, we must define these variables in the internalaccess methods,accessor is the equivalentgetter.The following example demonstrates the accessor method:

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造函数
   def initialize(w,h)
      @width, @height = w, h
   end

   # 访问器方法
   def printWidth
      @width
   end

   def printHeight
      @height
   end
end

# 创建对象
box = Box.new(10, 20)

# 使用访问器方法
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 to the access methods used to access the variable values, Ruby provides a way to set the variable external value of the class A, also known assetter method, defined as follows:

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end

   # 访问器方法
   def getWidth
      @width
   end
   def getHeight
      @height
   end

   # 设置器方法
   def setWidth=(value)
      @width = value
   end
   def setHeight=(value)
      @height = value
   end
end

# 创建对象
box = Box.new(10, 20)

# 使用设置器方法
box.setWidth = 30
box.setHeight = 50

# 使用访问器方法
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 : 30
Height of the box is : 50

Instance Methods

Defineinstance methods and other methods defined, they are using the defkeyword, but they can only be used by a class instance, as shown in the following examples. Their function is not limited to access instance variables, but also according to your needs to do more other tasks.

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造方法
   def initialize(w,h)
      @width, @height = w, h
   end
   # 实例方法
   def getArea
      @width * @height
   end
end

# 创建对象
box = Box.new(10, 20)

# 调用实例方法
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 variables class methods &

Class variables are all instances of a class shared variables.In other words, the class instance variables can be accessed all object instances. Class variable with two @ characters (@@) as a prefix, class variables must be initialized in the class definition, as shown in the following examples.

Class method def self.methodname ()definition, a class method to end delimiter. Class methods can be used with the class nameclassname.methodname form of call, as shown in the following examples:

#!/usr/bin/ruby -w

class Box
   # 初始化类变量
   @@count = 0
   def initialize(w,h)
      # 给实例变量赋值
      @width, @height = w, h

      @@count += 1
   end

   def self.printCount()
      puts "Box count is : #@@count"
   end
end

# 创建两个对象
box1 = Box.new(10, 20)
box2 = Box.new(30, 100)

# 调用类方法来输出盒子计数
Box.printCount()

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

Box count is : 2

to_s method

Any class has ato_s instance method that you define to return a string representation of the object.Here is a simple example, according to the width and height represent Box objects:

#!/usr/bin/ruby -w

class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end
   # 定义 to_s 方法
   def to_s
      "(w:#@width,h:#@height)"  # 对象的字符串格式
   end
end

# 创建对象
box = Box.new(10, 20)

# 自动调用 to_s 方法
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 you with three levels of protection instance methods, which arepublic, private or protected.Any access control application is not on Ruby instance and class variables.

  • Public Method: Public methods can be called any object.By default, methods are public, except for the initialize method is always private.
  • Private Methods: Private methods can not be accessed or viewed from outside the class.Only class methods can access private members.
  • Protected method: Protected method can only be called an object class and its subclasses.Access can only be carried out in an internal class and its subclasses.

Here is a simple example that demonstrates the three modifier syntax:

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end

   # 实例方法默认是 public 的
   def getArea
      getWidth() * getHeight
   end

   # 定义 private 的访问器方法
   def getWidth
      @width
   end
   def getHeight
      @height
   end
   # make them private
   private :getWidth, :getHeight

   # 用于输出面积的实例方法
   def printArea
      @area = getWidth() * getHeight
      puts "Big box area is : #@area"
   end
   # 让实例方法是 protected 的
   protected :printArea
end

# 创建对象
box = Box.new(10, 20)

# 调用实例方法
a = box.getArea()
puts "Area of the box is : #{a}"

# 尝试调用 protected 的实例方法
box.printArea()

When the above code is executed, it will produce the following results. Here, the first method call succeeds, but the second method will have 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, object-oriented programming is one of the most important concepts. Inheritance allows us to define a class based on another class, which makes creating and maintaining applications much easier.

Inheritance helps to reuse code and fast execution, unfortunately, Ruby does not support multiple inheritance, but Ruby supportmixins.mixin is like a particular implementation of multiple inheritance, multiple inheritance, only part of the interface is inheritable.

When you create a class, the programmer can specify a new class that inherits from an existing class of members, so do not write from scratch the new data members and member functions. The existing class is called thebase class or parent class, the new class is called the derived classes or subclasses.

Ruby also provides a subclass concept subclass that is inherited, the following example illustrates this concept. Extending a class syntax is very simple. Just add a <character name and the parent class to the class statement can. For example, the following defines a classBigBoxBox is a subclass:

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end
   # 实例方法
   def getArea
      @width * @height
   end
end

# 定义子类
class BigBox < Box

   # 添加一个新的实例方法
   def printArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end

# 创建对象
box = BigBox.new(10, 20)

# 输出面积
box.printArea()

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

Big box area is : 200

Method overloading

Although you can add new features in a derived class, but sometimes you may want to change the behavior has been defined in the parent class methods. Then you can keep the same method name, the function can be overloaded methods, as shown in the following examples:

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end
   # 实例方法
   def getArea
      @width * @height
   end
end

# 定义子类
class BigBox < Box

   # 改变已有的 getArea 方法
   def getArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end

# 创建对象
box = BigBox.new(10, 20)

# 使用重载的方法输出面积
box.getArea()

Run the above example output is:

Big box area is : 200

Operator Overloading

We want to use the + operator performs vector addition of two Box objects, use the * operator to the width and height of the Box multiplied using unary operator - the width and height of Box negated. Here is a version of the math class with Box Operator definition:

class Box
  def initialize(w,h) # 初始化 width 和 height
    @width,@height = w, h
  end

  def +(other)         # 定义 + 来执行向量加法
    Box.new(@width + other.width, @height + other.height)
  end

  def -@               # 定义一元运算符 - 来对 width 和 height 求反
    Box.new(-@width, -@height)
  end

  def *(scalar)        # 执行标量乘法
    Box.new(@width*scalar, @height*scalar)
  end
end

Frozen object

Sometimes, we want to prevent an object is changed. In the Object, freeze method can achieve this, it can effectively put an object into a constant. Any object can be frozen by callingObject.freeze.Frozen object can not be modified, that is, you can not change its instance variables.

You can useObject.frozen? Method to check whether a given object has been frozen.If the object has been frozen, the method returns true, otherwise it returns a false value. The following example illustrates this concept:

#!/usr/bin/ruby -w

# 定义类
class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end

   # 访问器方法
   def getWidth
      @width
   end
   def getHeight
      @height
   end

   # 设置器方法
   def setWidth=(value)
      @width = value
   end
   def setHeight=(value)
      @height = value
   end
end

# 创建对象
box = Box.new(10, 20)

# 让我们冻结该对象
box.freeze
if( box.frozen? )
   puts "Box object is frozen object"
else
   puts "Box object is normal object"
end

# 现在尝试使用设置器方法
box.setWidth = 30
box.setHeight = 50

# 使用访问器方法
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 constants

You can define a constant internal class, by a direct numeric or string value to a variable definition, which does not require the constant use @ or @@. By convention, the name of the constant use uppercase.

Once a constant is defined, you can not change its value, you can directly access the internal constants in the class, as is access to the same variable, but if you want to access external constant class, then you must use theclassname :: constant , as shown in the following examples.

#!/usr/bin/ruby -w

# 定义类
class Box
   BOX_COMPANY = "TATA Inc"
   BOXWEIGHT = 10
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end
   # 实例方法
   def getArea
      @width * @height
   end
end

# 创建对象
box = Box.new(10, 20)

# 调用实例方法
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

Class constants can be inherited, but also the same as the instance method is overloaded.

Use allocate create objects

There may be a case, you want to create an object without calling the constructorinitialize the object, that object is created using the new method, in this case, you can call allocate to create an uninitialized object, as the following examples as follows:

#!/usr/bin/ruby -w

# 定义类
class Box
   attr_accessor :width, :height

   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end

   # 实例方法
   def getArea
      @width * @height
   end
end

# 使用 new 创建对象
box1 = Box.new(10, 20)

# 使用 allocate 创建两一个对象
box2 = Box.allocate

# 使用 box1 调用实例方法
a = box1.getArea()
puts "Area of the box is : #{a}"

# 使用 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

Ruby's self and Java this are similar, but different. Java methods are referenced in an instance method, so this usually refers to the current object. The Ruby code line by line, so in a different context (context) self have a different meaning. Let's take a look at the following examples:

#!/usr/bin/ruby -w

class Box
   # 输出类信息
   puts "Class of self = #{self.class}"
   puts "Name of self = #{self.name}"
end

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

Class of self = Class
Name of self = Box

This means that the class can be defined by the class as the current object to execute, but also means that meta-class and the parent class method definition during the process execution is available.