Ruby创建构造器技巧分享
创始人
2024-06-16 07:40:13
0

虽然Ruby语言中没有现成的构造器,不过我们依然可以实现Ruby创建构造器的功能。那么,接下来我们将会为大家介绍Ruby创建构造器具体的实现技巧。#t#

  1. class ColoredRectangle    
  2. def initialize(r, g, b, s1, s2)   
  3. @r, @g, @b, @s1, @s2 = r, g, b, s1, s2    
  4. end  
  5. def ColoredRectangle.white_rect(s1, s2)   
  6. new(0xff, 0xff, 0xff, s1, s2)    
  7. end  
  8. def ColoredRectangle.gray_rect(s1, s2)    
  9. new(0x88, 0x88, 0x88, s1, s2)   
  10. end  
  11. def ColoredRectangle.colored_square(r, g, b, s)   
  12. new(r, g, b, s, s)    
  13. end   
  14. def ColoredRectangle.red_square(s)    
  15. new(0xff, 0, 0, s, s)    
  16. end  
  17. def inspect   
  18. "#@r #@g #@b #@s1 #@s2"   
  19. end  
  20. end  
  21. a = ColoredRectangle.new(0x88, 0xaa, 0xff, 20, 30)   
  22. b = ColoredRectangle.white_rect(15,25)   
  23. c = ColoredRectangle.red_square(40) 

如果Ruby创建构造器属性过多,我们可以使用

  1. class PersonalComputer   
  2. attr_accessor :manufacturer,    
  3. :model, :processor, :clock,    
  4. :ram, :disk, :monitor,   
  5. :colors, :vres, :hres, :net   
  6. def initialize(&block)   
  7. instance_eval &block    
  8. end    
  9. # Other methods   
  10. end   
  11. desktop = PersonalComputer.new do   
  12. self.manufacturer = "Acme"   
  13. self.model = "THX-1138"   
  14. self.processor = "986"    
  15. self.clock = 9.6 # GHz   
  16. self.ram = 16 # Gb    
  17. self.disk = 20 # Tb   
  18. self.monitor = 25 # inches    
  19. self.colors = 16777216   
  20. self.vres = 1280   
  21. self.hres = 1600    
  22. self.net = "T3"   
  23. end    
  24. p desktop 

怎么样,这样Ruby创建构造器的方法是不是漂亮很多呢?!

注意:block中的self是必须的。

你也可以使用undef方法动态删除你的需要的方法。

 

  1. desktop = PersonalComputer.new do   
  2. self.manufacturer = "Acme"   
  3. self.model = "THX-1138"   
  4. undef model   
  5. end   
  6. p desktop.model #报错 

以上就是我们为大家介绍的有关Ruby创建构造器技巧应用。

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...