Ruby语言在实际使用中会创建许多类,来满足我们的整体编程需求。对于初学者来说,我们必须熟练地掌握创建类的方法,比如Ruby创建可参数化类等等。#t#
如果我们要创建很多类,这些类只有类成员的初始值不同,我们很容易想起:
- class IntelligentLife # Wrong
way to do this! - @@home_planet = nil
- def IntelligentLife.home_planet
- @@home_planet
- end
- def IntelligentLife.home_planet=(x)
- @@home_planet = x
- end
- #...
- end
- class Terran < IntelligentLife
- @@home_planet = "Earth"
- #...
- end
- class Martian < IntelligentLife
- @@home_planet = "Mars"
- #...
- end
这种Ruby创建可参数化类方式是错误的,实际上Ruby中的类成员不仅在这个类中被所有对象共享,实际上会被整个继承体系共享,所以我们调用Terran.home_planet,会输出“Mars”,而我们期望的是Earth一个可行的方法:
我们可以通过class_eval在运行时延迟求值来达到目标:
- class IntelligentLife
- def IntelligentLife.home_planet
- class_eval("@@home_planet")
- end
- def IntelligentLife.home_planet=(x)
- class_eval("@@home_planet = #{x}")
- end
- #...
- end
- class Terran < IntelligentLife
- @@home_planet = "Earth"
- #...
- end
- class Martian < IntelligentLife
- @@home_planet = "Mars"
- #...
- end
- puts Terran.home_planet # Earth
- puts Martian.home_planet # Mars
最好的Ruby创建可参数化类方法:
我们不使用类变量,而是使用类实例变量:
- class IntelligentLife
- class << self
- attr_accessor :home_planet
- end
- #...
- end
- class Terran < IntelligentLife
- self.home_planet = "Earth"
- #...
- end
- class Martian < IntelligentLife
- self.home_planet = "Mars"
- #...
- end
- puts Terran.home_planet # Earth
- puts Martian.home_planet # Mars