一个常量一旦被定义就不能改变它的值,但可以在类里像常量一样直接访问,但如果要访问一个类之外的常量,那么要使用类名::常量,所示在下面的例子。
#!/usr/bin/ruby -w
# define a class
class Box
BOX_COMPANY = "TATA Inc"
BOXWEIGHT = 10
# 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}"
puts Box::BOX_COMPANY
puts "Box weight is: #{Box::BOXWEIGHT}"
当上面的代码执行时,它会产生以下结果:
Area of the box is : 200 TATA Inc Box weight is: 10
类常量继承和实例方法一样,可以覆盖。
创建对象使用分配:
当创建一个对象,而不调用它的构造函数初始化,即可能有一个情况:采用 new 方法,在这种情况下可以调用分配,这将创造一个未初始化的对象,看下面的例子:
#!/usr/bin/ruby -w
# define a class
class Box
attr_accessor :width, :height
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end
# create an object using new
box1 = Box.new(10, 20)
# create another object using allocate
box2 = Box.allocate
# call instance method using box1
a = box1.getArea()
puts "Area of the box is : #{a}"
# call instance method using 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
类信息:
如果类定义的可执行代码,这意味着他们在执行的上下文中一些对象:自身都必须引用的东西。让我们来看看它是什么。
#!/usr/bin/ruby -w
class Box
# print class information
puts "Type of self = #{self.type}"
puts "Name of self = #{self.name}"
end
当上面的代码执行时,它会产生以下结果:
Type of self = Class Name of self = Box
这意味着,一个类的定义,作为当前对象的类并执行。在元类和其超类的方法将在执行过程中使用的方法定义。










