Ruby的面向对象编程的基础教程

2019-09-25 09:45:47王冬梅

类常量

您可以在类的内部定义一个常量,通过把一个直接的数值或字符串值赋给一个变量来定义的,常量的定义不需要使用 @ 或 @@。按照惯例,常量的名称使用大写。

一旦常量被定义,您就不能改变它的值,您可以在类的内部直接访问常量,就像是访问变量一样,但是如果您想要在类的外部访问常量,那么您必须使用 classname::constant,如下面实例所示。

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

当上面的代码执行时,它会产生以下结果:

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

类常量可被继承,也可像实例方法一样被重载。
使用 allocate 创建对象

可能有一种情况,您想要在不调用对象构造器 initialize 的情况下创建对象,即,使用 new 方法创建对象,在这种情况下,您可以调用 allocate 来创建一个未初始化的对象,如下面实例所示:

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

当上面的代码执行时,它会产生以下结果:

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

类信息

如果类定义是可执行代码,这意味着,它们可在某个对象的上下文中执行,self 必须引用一些东西。让我们来看看下面的实例:.

#!/usr/bin/ruby -w
 
class Box
  # 输出类信息
  puts "Type of self = #{self.type}"
  puts "Name of self = #{self.name}"
end

当上面的代码执行时,它会产生以下结果:

Type of self = Class
Name of self = Box

这意味着类定义可通过把该类作为当前对象来执行,同时也意味着元类和父类中的该方法在方法定义执行期间是可用的。