新聞中心
雖然Ruby語言中沒有現(xiàn)成的構(gòu)造器,不過我們依然可以實現(xiàn)Ruby創(chuàng)建構(gòu)造器的功能。那么,接下來我們將會為大家介紹Ruby創(chuàng)建構(gòu)造器具體的實現(xiàn)技巧。#t#

成都創(chuàng)新互聯(lián)服務(wù)項目包括元寶山網(wǎng)站建設(shè)、元寶山網(wǎng)站制作、元寶山網(wǎng)頁制作以及元寶山網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,元寶山網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到元寶山省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
- class ColoredRectangle
- def initialize(r, g, b, s1, s2)
- @r, @g, @b, @s1, @s2 = r, g, b, s1, s2
- end
- def ColoredRectangle.white_rect(s1, s2)
- new(0xff, 0xff, 0xff, s1, s2)
- end
- def ColoredRectangle.gray_rect(s1, s2)
- new(0x88, 0x88, 0x88, s1, s2)
- end
- def ColoredRectangle.colored_square(r, g, b, s)
- new(r, g, b, s, s)
- end
- def ColoredRectangle.red_square(s)
- new(0xff, 0, 0, s, s)
- end
- def inspect
- "#@r #@g #@b #@s1 #@s2"
- end
- end
- a = ColoredRectangle.new(0x88, 0xaa, 0xff, 20, 30)
- b = ColoredRectangle.white_rect(15,25)
- c = ColoredRectangle.red_square(40)
如果Ruby創(chuàng)建構(gòu)造器屬性過多,我們可以使用
- 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創(chuàng)建構(gòu)造器的方法是不是漂亮很多呢?!
注意:block中的self是必須的。
你也可以使用undef方法動態(tài)刪除你的需要的方法。
- desktop = PersonalComputer.new do
- self.manufacturer = "Acme"
- self.model = "THX-1138"
- undef model
- end
- p desktop.model #報錯
以上就是我們?yōu)榇蠹医榻B的有關(guān)Ruby創(chuàng)建構(gòu)造器技巧應(yīng)用。
標(biāo)題名稱:Ruby創(chuàng)建構(gòu)造器技巧分享
當(dāng)前URL:http://fisionsoft.com.cn/article/ccdjgje.html


咨詢
建站咨詢
