如何正确实现Ruby创建可参数化类

开发 开发工具
Ruby创建可参数化类的实现对于刚刚接触Ruby语言不久的朋友是一个比较难掌握的知识,我们需要不断的从实践中去了解其中的含义。

Ruby语言在实际使用中会创建许多类,来满足我们的整体编程需求。对于初学者来说,我们必须熟练地掌握创建类的方法,比如Ruby创建可参数化类等等。#t#

如果我们要创建很多类,这些类只有类成员的初始值不同,我们很容易想起:

  1. class IntelligentLife # Wrong 
    way to do this!   
  2. @@home_planet = nil   
  3. def IntelligentLife.home_planet   
  4. @@home_planet   
  5. end   
  6. def IntelligentLife.home_planet=(x)   
  7. @@home_planet = x   
  8. end   
  9. #...   
  10. end   
  11. class Terran < IntelligentLife   
  12. @@home_planet = "Earth"   
  13. #...   
  14. end   
  15. class Martian < IntelligentLife   
  16. @@home_planet = "Mars"   
  17. #...   
  18. end  

这种Ruby创建可参数化类方式是错误的,实际上Ruby中的类成员不仅在这个类中被所有对象共享,实际上会被整个继承体系共享,所以我们调用Terran.home_planet,会输出“Mars”,而我们期望的是Earth一个可行的方法:

我们可以通过class_eval在运行时延迟求值来达到目标:

  1. class IntelligentLife   
  2. def IntelligentLife.home_planet   
  3. class_eval("@@home_planet")   
  4. end   
  5. def IntelligentLife.home_planet=(x)   
  6. class_eval("@@home_planet = #{x}")   
  7. end   
  8. #...   
  9. end   
  10. class Terran < IntelligentLife   
  11. @@home_planet = "Earth"   
  12. #...   
  13. end   
  14. class Martian < IntelligentLife   
  15. @@home_planet = "Mars"   
  16. #...   
  17. end   
  18. puts Terran.home_planet # Earth   
  19. puts Martian.home_planet # Mars  

最好的Ruby创建可参数化类方法:

我们不使用类变量,而是使用类实例变量:

  1. class IntelligentLife   
  2. class << self   
  3. attr_accessor :home_planet   
  4. end   
  5. #...   
  6. end   
  7. class Terran < IntelligentLife   
  8. self.home_planet = "Earth"   
  9. #...   
  10. end   
  11. class Martian < IntelligentLife   
  12. self.home_planet = "Mars"   
  13. #...   
  14. end   
  15. puts Terran.home_planet # Earth   
  16. puts Martian.home_planet # Mars  

 

责任编辑:曹凯 来源: jb51.net
相关推荐

2010-01-06 15:56:18

.Net Framew

2009-12-08 14:31:31

PHP命令行读取参数

2009-12-21 10:09:26

WCF创建客户端服务对

2009-12-29 18:09:00

Silverlight

2010-02-25 10:10:29

WCF使用Header

2010-02-25 13:48:23

WCF动态创建代码

2009-12-03 11:11:57

PHP网站优化

2009-12-11 17:52:21

PHP获取博客数据

2009-12-07 18:42:55

PHP与Javascr

2010-01-22 13:08:50

VB.NET创建数组

2009-12-04 12:51:27

PHP functio

2009-12-09 16:49:09

PHP显示文章发布时间

2010-04-29 17:31:56

Oracle存储过程

2010-03-04 15:12:33

Python算法

2010-03-04 11:12:02

Python AOP

2010-01-15 16:03:48

VB.NET重载Win

2020-10-15 10:51:05

云计算IT技术

2010-02-24 10:07:48

WCF跨越边界

2010-02-26 11:22:16

LitwareHR使用

2010-02-24 13:48:44

MSMQ使用WCF
点赞
收藏

51CTO技术栈公众号