Ruby创建构造器技巧分享

开发 开发工具
Ruby语言在世纪操作中经常会遇到有关构造器应用的相关情况。不过Ruby并没有构造器,我们需要自己来完成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创建构造器技巧应用。

责任编辑:曹凯 来源: 博客园
相关推荐

2009-12-15 10:23:23

Ruby应用技巧

2009-03-19 09:24:50

XML标记XML结构XML入门

2009-12-18 10:47:16

Ruby装饰模式

2009-12-15 18:24:02

Ruby连接到orac

2009-12-15 18:15:24

Ruby连接到LDAP

2009-12-16 10:10:16

Ruby打开关闭文件

2009-12-18 14:10:29

Ruby访问剪贴板

2009-12-16 11:04:51

Ruby操作文件权限

2009-12-16 15:46:41

Ruby on rai

2009-12-16 10:49:42

Ruby操作二进制文件

2010-08-05 09:09:02

路由器配置

2009-06-12 18:26:09

2010-08-05 09:15:04

路由器配置

2009-12-17 09:14:14

Ruby on Rai

2009-12-30 13:37:24

Silverlight

2009-12-14 09:33:04

Ruby安装

2010-01-22 11:02:30

VB.NET创建新变量

2010-01-13 15:52:59

VB.NET浮动窗体

2009-12-18 17:01:37

Ruby基础代码

2009-12-16 16:37:59

Ruby on Rai
点赞
收藏

51CTO技术栈公众号