Prev - DUP - Next - TOC

More on methods (for access control)


In the previous chapter, we said that ruby has no function, but it does have what is called a method. Though, there are several sorts of methods so it is a little complicated. These the sorts of mothods are named `access controls', which play the roll of the restriction in method calling.

First, defining the function (method) in the top level,

 ruby> def sqr(n)
 ruby|   n * n
 ruby| end
 nil
 ruby> sqr(5)
 25

`def' appearing outside of class definition acts to append a method to the Object class. The Object class is inherited by all other classes, so it means that sqr can be used in all the classes.

Now the all classes must be able to call sqr, then we try to call sqr to `self':

 ruby> self.sqr(5)
 ERR: private method `sqr' called for main(Object)

Oh, an error occurred... that was not how we understood it!

The fact is that the methods defined in the top level can be called with only function call style. It is the conclusion of the policy: "What method looks function must behave function".

So it causes a different error message than when undefined methods are called.

 ruby> undefined_method(13)
 ERR: undefined method `undefined_method' for main(Object)

Aha! that isn't `undefined' but `private'. Conversely, methods which are defined in a class can be called freely.

 ruby> class Test
 ruby|   def foo
 ruby|     print "foo\n"
 ruby|   end
 ruby|   def bar
 ruby|     print "bar -> "
 ruby|     foo
 ruby|   end
 ruby| end
 nil
 ruby> test = Test.new
 #<Test:0xbae88>
 ruby> test.foo
 foo
 nil
 ruby> test.bar
 bar -> foo
 nil

In the above example, the `bar' method calls `foo' in function style.

If a method is called in function style only, the calls are within the class or the its subclass, so it works like a `protected' method in C++. In other words, we may forbidden to access from outside.

To change the accessible property of a method, we use the methods `private' and `public'.

 ruby> class Test2
 ruby|   def foo
 ruby|     print "foo\n"
 ruby|   end
 ruby|   private :foo
 ruby|   def bar
 ruby|     print "bar -> "
 ruby|     foo
 ruby|   end
 ruby| end
 nil
 ruby> test2 = Test2.new
 #<Test2:0xbb440>
 ruby> test2.foo
 ERR: private method `foo' called for #<Test2:0x8a658>(Test2)
 ruby> test2.bar
 bar -> foo
 nil

Adding the `private :foo' line, you see that the foo method isn't available with `test.foo'. Additionally, to open a method which was made `private', use `public :the_method_name'. Don't forget the colon `:' leading the method name when you specify. If you missed putting `:' the following literal is regarded as reference to a local variable but not as a method name, and it makes complicated errors.

A private method warks similarly to what we call function. Though, yet it is very much a method, so the methods with same name are allowed between defferent classes; That is a disparity against the concept of ordinary function.


Prev - DUP - Next - TOC