There is no constructor like C ++ or Ruby in Ruby, but we can still create multiple constructor similar to this:
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" endenda = coloredrectangle. new (0x88, 0xaa, 0xff, 20, 30) B = coloredrectangle. white_rect (15,25) C = coloredrectangle. red_square (40)
If there are too many attributes, we can use
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
How are you doing ?!
Note: The self in the block is required.
You can also use the UNDEF method to dynamically Delete the methods you need.
desktop = personalcomputer. new do self. manufacturer = "Acme" self. model = "THX-1138" UNDEF model end P desktop. model # error