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}"
当上面的代码执行时,它会产生以下结果:
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
类的方法和变量:
类变量是一个变量,这是一个类的所有实例之间共享。该变量是一个实例,它是可访问对象实例。两个@字符类变量带有前缀(@@)。在类定义类变量必须初始化,如下所示。










