From: Dave Thomas Date: 2000-05-11T00:06:19-05:00 Subject: [ruby-talk:02730] Re: Public/Private clarification Albert Wagner writes: > I have read the documentation and am now browsing sample code to learn > more about ruby. The following code, export.rb, triggers some questions: > > 1) What does "public :printf" do in class Foo? 'printf' is a module function in Kernel, and the Kernel module is included in class Object. The printf method is therefore available throughout Ruby as either Kernel::printf "hello\n" # module method or printf "hello\n" # instance method However, printf is private, which means it must be called in functional form (ie without a receiver). Something like self.printf ... would raise an error. In class Foo, printf is made public, which means it can then be called with an instance of Foo (or a subclass of Foo) as a receiver. class Foo public :printf end f = Foo.new f.printf "hello\n" > 2) I thought a module defined outside a class was, by default, attached > to Object and was private, such as "def foobar" below. Why is a > redefinition of class Foo required to change foobar() to public? > Why is the "public :foobar" statement not immediatly after the def > of foobar? Does this mean that public/private access to an given > Object method be private in one subclass and public in another? Maybe a different example might make it clearer. class Base def aMethod puts "Got here" end private :aMethod end class Derived1 < Base public :aMethod end class Derived2 < Base end Derived1.new.aMethod # -> Got here Derived2.new.aMethod # -> private method `aMethod' called... # Now change the base class class Base def aMethod puts "changed" end end Derived1.new.aMethod # -> changed Derived2.new.aMethod # -> changed If you're in class X and change the visibility of a method defined in an ancestor class, Ruby effectively defines a proxy method in X which calls the ancestor method. That proxy method is then given the assigned visibility. That way, the same method can have different visibilities in different subclasses. Neat, eh? Dave -- ___________________________________________________________________________ | The Pragmatic Programmers, LLC | http://www.pragmaticprogrammer.com | | Read "The Pragmatic Programmer" | www.pragmaticprogrammer.com/ppbook/ | ---------------------------------------------------------------------------