在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
在ruby中没有像c++或者ruby中的构造器,可是我们依然能够创建出类似的多个构造器:
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) 如果属性过多,我们可以使用 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 怎么样,这样是不是漂亮很多呢?! 注意:block中的self是必须的。 你也可以使用undef方法动态删除你的需要的方法。 desktop = PersonalComputer.new do self.manufacturer = "Acme" self.model = "THX-1138" undef model end p desktop.model #报错 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论