快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

足球电台广播:ruby模拟多个构造器



在ruby中没有像c++或者ruby中的构造器,可是我们依然能够创建出类似的多个构造器:

class Co足球电台广播loredRectangle

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.wh足球电台广播ite_rect(15,25)

c = ColoredRectangle.red_square(40)

假如属性过多,我们可以应用

class PersonalComputer

attr_accessor :manufacturer,

:model, :processor, :clock,

:ram, :disk, :monitor,

:colors, :vres, :hres, :net

def initialize(&block)

instance_eval &bl足球电台广播ock

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 = 1足球电台广播280

self.hres = 1600

self.net = "T3"

end

p desktop

怎么样,这样是不是漂亮很多呢?!

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

你也可以应用undef措施动态删除你的必要的措施。

desktop = PersonalComputer.new do

self.manufacturer = "Acme"

self.model = "THX-1138"

undef model

end

p deskt足球电台广播op.model #报错

您可能还会对下面的文章感兴趣: