In many cases, when you design your applicationProgramYou may want to implement a method that is only used inside an object rather than other objects. Ruby provides three keywords to restrict access to methods.
- · PRIVATE: Only methods accessible to this object.
- · Protected: a method that can be accessed by this object and its class instances and directly inherited sub-classes.
- · Public: the method that can be accessed by any object (public is the default setting for all methods ).
These keywords are inserted between two methodsCode. All methods defined from the private keyword are private until another accesskey keyword appears in the code. For example, in the following code, the accessor and area methods are both public by default, while the grow method is private. Note that the doublesize method is explicitly specified as public. The initialize method of a class is automatically private.
Class rectangle Attr_accessor: height,: width Def initialize (HgT, wdth) @ Height = HgT @ Width = wdth End Def area () @ Height * @ width End Private # start to define private methods Def grow (heightmultiple, widthmultiple) @ Height = @ height * heightmultiple @ Width = @ width * widthmultiple Return "New Area:" + area (). to_s End Public # define public methods again Def doublesize () Grow (2, 2) End End |
As shown below, doublesize can be executed on the object, but any direct call to grow is rejected and an error is returned.
IRB (main): 075: 0> rect2 = rectangle. New (3, 4) ==#< Rectangle: 0x59a3088 @ width = 4, @ Height = 3> IRB (main): 076: 0> rect2.doublesize () => "New Area: 48" IRB (main): 077: 0> rect2.grow () Nomethoderror: Private method 'grow' called for # <rectangle: 0x59a3088 @ width = 8, @ Height = 6> From (IRB): 77 From: 0 |
By default, instances and class variables are private in Ruby unless the property accessor and mutator are provided.