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

  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创建构造器属性过多,我们可以使用

class PersonalComputer   


attr_accessor :manufacturer,    


:model, :processor, :clock,    


:ram, :disk, :monitor,   


:colors, :vres, :hres, :net   


def initialize(&block)   


instance_eval &block    


end    


# Other methods   


end   



desktop = PersonalComputer.new do   




self.manufacturer = "Acme"   




self.model = "THX-1138"   




self.processor = "986"    




self.clock = 9.6 # GHz   




self.ram = 16 # Gb    




self.disk = 20 # Tb   




self.monitor = 25 # inches    




self.colors = 16777216   




self.vres = 1280   




self.hres = 1600    




self.net = "T3"   



end    


p desktop 

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

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

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