类方法的定义使用: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}"
当上面的代码执行时,它会产生以下结果:
String representation of box is : (w:10,h:20)
访问控制:
Ruby提供了三个级别的保护实例方法的级别:public, private 和 protected。 Ruby没有应用实例和类变量的任何访问控制权。
Public Methods: 任何人都可以被称为public方法。方法默认为公用初始化,这始终是 private 除外。 .
Private Methods: private方法不能被访问,或者甚至从类的外部浏览。只有类方法可以访问私有成员。
Protected Methods: 受保护的方法可以被调用,只能通过定义类及其子类的对象。访问保存在类内部。
以下是一个简单的例子来说明三个访问修饰符的语法:
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method by default it is public
def getArea
getWidth() * getHeight
end
# define private accessor methods
def getWidth










