自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Ruby創(chuàng)建構(gòu)造器技巧分享

開發(fā) 開發(fā)工具
Ruby語言在世紀操作中經(jīng)常會遇到有關(guān)構(gòu)造器應用的相關(guān)情況。不過Ruby并沒有構(gòu)造器,我們需要自己來完成Ruby創(chuàng)建構(gòu)造器的步驟。

雖然Ruby語言中沒有現(xiàn)成的構(gòu)造器,不過我們依然可以實現(xiàn)Ruby創(chuàng)建構(gòu)造器的功能。那么,接下來我們將會為大家介紹Ruby創(chuàng)建構(gòu)造器具體的實現(xiàn)技巧。#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創(chuàng)建構(gòu)造器屬性過多,我們可以使用

  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創(chuàng)建構(gòu)造器的方法是不是漂亮很多呢?!

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

你也可以使用undef方法動態(tài)刪除你的需要的方法。

 

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

以上就是我們?yōu)榇蠹医榻B的有關(guān)Ruby創(chuàng)建構(gòu)造器技巧應用。

責任編輯:曹凱 來源: 博客園
相關(guān)推薦

2009-12-15 10:23:23

Ruby應用技巧

2009-12-18 10:47:16

Ruby裝飾模式

2009-12-15 18:24:02

Ruby連接到orac

2009-03-19 09:24:50

XML標記XML結(jié)構(gòu)XML入門

2009-12-15 18:15:24

Ruby連接到LDAP

2009-12-16 10:10:16

Ruby打開關(guān)閉文件

2009-12-18 14:10:29

Ruby訪問剪貼板

2009-12-16 11:04:51

Ruby操作文件權(quán)限

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-30 13:37:24

Silverlight

2009-12-17 09:14:14

Ruby on Rai

2009-12-14 09:33:04

Ruby安裝

2010-01-22 11:02:30

VB.NET創(chuàng)建新變量

2010-01-13 15:52:59

VB.NET浮動窗體

2009-12-18 17:01:37

Ruby基礎代碼

2009-12-14 18:23:38

Ruby DSL測試
點贊
收藏

51CTO技術(shù)棧公眾號