Ruby创建构造器技巧分享

虽然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创建构造器技巧应用。

当前名称:Ruby创建构造器技巧分享
本文链接:http://www.shufengxianlan.com/qtweb/news21/547021.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联