Ruby創(chuàng)建構(gòu)造器技巧分享
作者:佚名
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#
- 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)造器技巧應用。
責任編輯:曹凱
來源:
博客園