Ruby面向对象编程详解

2019-09-25 09:48:05丽君

# 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

这意味着,一个类的定义,作为当前对象的类并执行。在元类和其超类的方法将在执行过程中使用的方法定义。