Ruby - Protected and Private Methods in Descendant Classes

Introduction

The following code created a MyClass object called myob and a MyOtherClass object, myotherob, where MyOtherClass descends from MyClass:

class MyClass
    private
        def priv( aStr )
            return aStr.upcase
        end
    protected
        def prot( aStr )
            return aStr << '!!!!!!'
        end
    public
        def exclaim( anOb )  # calls a protected method
            puts( anOb.prot( "This is a #{anOb.class} - hurrah" ) )
        end
        def shout( anOb )    # calls a private method
            puts( anOb.priv( "This is a #{anOb.class} - hurrah" ) )
        end
end
class MyOtherClass < MyClass
end
class MyUnrelatedClass
end

myob = MyClass.new
myotherob = MyOtherClass.new
myunrelatedob = MyUnrelatedClass.new

myob.shout( myotherob )     # fails

Here the shout method calls the private method priv on the argument object:

def shout( anOb )    # calls a private method
   puts( anOb.priv( "This is a #{anOb.class} - hurrah" ) )
end

This won't work! The priv method is private.

myotherob.shout( myob )     # fails

Related Topic