虽然Ruby语言中没有现成的构造器,不过我们依然可以实现Ruby创建构造器的功能。那么,接下来我们将会为大家介绍Ruby创建构造器具体的实现技巧。#t#
如果Ruby创建构造器属性过多,我们可以使用
- 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创建构造器的方法是不是漂亮很多呢?!
注意:block中的self是必须的。
你也可以使用undef方法动态删除你的需要的方法。
- desktop = PersonalComputer.new do
- self.manufacturer = "Acme"
- self.model = "THX-1138"
- undef model
- end
- p desktop.model #报错
以上就是我们为大家介绍的有关Ruby创建构造器技巧应用。