Ruby元编程学习笔记(一)

Ruby的class关键字更像是一个作用于操作符,而不是类型声明语句。class关键字的核心任务是把你带到类的上下文中,上你可以在里面定义方法。Ruby中对象的类和它的实例变量没有关系,当给实例变量赋值时,它们就突然出现了,因此对于同一个类,可以创建具有不同实例变量的对象。例如:

class MyClass
  def my_method
    @v = 1
  end
end

obj1 = MyClass.new
print obj1.instance_variables # []
obj2 = MyClass.new
obj2.my_method
print obj2.instance_variables #[:@v]

类的实例方法等于对象的方法:

puts MyClass.instance_methods == obj1.methods # true
puts MyClass.instance_methods == obj2.methods # true

类本身也是对象:

puts "obj1's class is #{obj1.class}"
puts "MyClass's class is #{MyClass.class}"
puts "MyClass's superclass is #{MyClass.superclass}"
puts "Class's class is #{Class.class}"
puts "Class's superclass is #{Class.superclass}"
puts "Module's class is #{Module.class}"
puts "Module's superclass is #{Module.superclass}"
puts "Object's class is #{Object.class}"
puts "Object's superclass is #{Object.superclass}"
puts "BasicObject's class is #{BasicObject.class}"
puts "BasicObject's superclass is #{BasicObject.superclass}"

# output:
# obj1's class is MyClass
# MyClass's class is Class
# MyClass's superclass is Object
# Class's class is Class
# Class's superclass is Module
# Module's class is Class
# Module's superclass is Object
# Object's class is Class
# Object's superclass is BasicObject
# BasicObject's class is Class
# BasicObject's superclass is nil

类图: