进一步深入Ruby中的类与对象概念

2019-09-25 09:43:00丽君

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

类似的存取方法用于访问的变量值,Ruby提供了一种方法来从类的外部设置这些变量的值,那就是setter方法??,定义如下:

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

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

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

实例方法:

也以同样的方式,因为我们使用def关键字定义其他方法,并按下图所示仅对使用一个类的实例,它们可以被用来定义该实例方法。它们的功能不局限于访问实例变量,他们也可以按要求做更多的事情。

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

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

Area of the box is : 200

类的方法和变量:

类变量是一个变量,这是一个类的所有实例之间共享。该变量是一个实例,它是可访问对象实例。两个@字符类变量带有前缀(@@)。在类定义类变量必须初始化,如下所示。

类方法的定义使用:def self.methodname() 以 end 字符结束,将被称为使用classname.methodname类名,在下面的例子所示:

#!/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()

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

Box count is : 2

 to_s 方法:

所定义的任何类的实例应该有一个 to_s 方法返回一个字符串形式表示对象。下面以一个简单的例子来表示一个Box对象,在宽度和高度方面:

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