Ruby中,在方法中定义类方法或实例方法的举例

来源:互联网 发布:什么是数据清洗 编辑:程序博客网 时间:2024/05/22 06:28
class Cdef instance_methodp "instance_method"#在实例方法中定义的另一个实例方法def another_instance_methodp "another_instance_method"endanother_instance_method#在实例方法中定义的类方法def C.another_class_method#这里不能用self.another_class_method,因为在instance_method里,self是instancep "another_class_method"end#another_class_method#error,不能使用instance调用class methodC.another_class_methodenddef self.class_methoddef yet_another_instance_methodp "yet_another_instance_method"end#yet_another_instance_method#error,在class_method里,self是class,而不是instance#在实例方法中定义的类方法def self.yet_another_class_method#这里就可以使用self.yet_another_class_method,因为在class_method里,self是classp "another_class_method"endanother_class_methodC.another_class_methodendendc=C.new#c.another_class_method#error,类方法,不能使用实例调用c.instance_methodp "================="c.another_instance_methodC.another_class_methodC.class_method