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

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

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

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

与用于访问变量值的访问器方法类似,Ruby 提供了一种在类的外部设置变量值的方式,也就是所谓的设置器方法,定义如下:

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

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

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

实例方法

实例方法的定义与其他方法的定义一样,都是使用 def 关键字,但它们只能通过类实例来使用,如下面实例所示。它们的功能不限于访问实例变量,也能按照您的需求做更多其他的任务。

#!/usr/bin/ruby -w
 
# 定义类
class Box
  # constructor method
  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}"

当上面的代码执行时,它会产生以下结果:
Area of the box is : 200
类方法 & 类变量

类变量是在类的所有实例中共享的变量。换句话说,类变量的实例可以被所有的对象实例访问。类变量以两个 @ 字符(@@)作为前缀,类变量必须在类定义中被初始化,如下面实例所示。

类方法使用 def self.methodname() 定义,类方法以 end 分隔符结尾。类方法可使用带有类名称的 classname.methodname 形式调用,如下面实例所示:
#!/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()

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

Box count is : 2

to_s 方法

您定义的任何类都有一个 to_s 实例方法来返回对象的字符串表示形式。下面是一个简单的实例,根据 width 和 height 表示 Box 对象:

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