stardiviner
7/5/2014 - 10:59 AM

Ruby methods visibility

Ruby methods visibility

#!/usr/bin/env ruby

class A                              #
  def test                           #
    protected_mth                    #
    private_mth                      #
                                     #
    self.protected_mth               #-+
    # self.private_mth     # wrong   # |
                                     # |__ you can specify instance object in defining class and its sub-classes.
    obj = B.new                      # |
    obj.protected_mth                # |
    # obj.private_mth       # wrong  #-+
  end                                #
                                     #
  protected                          #
  def protected_mth                  #
    puts "#{self.class}-protected"   #
  end                                #
                                     #
  private                            #
  def private_mth                    #
    puts "#{self.class}-private"     #
  end                                #
end                                  #
                                     #
class B < A                          #
  def test                           #
    protected_mth                    # ---> Can be invoked only by /objects of the defining class and its sub-classes/.
    private_mth                      # ---> Can't be called with an /explicit receiver/.
                                     #      The /receiver/ is always the /current object/, also known as [self].
                                     #      This means private method only can be invoked in the context of current object.
    self.protected_mth               # ---> Access is kept within the family. You can specify instance object in defining class and its sub-classes.
    # self.private_mth     # wrong   #
                                     #
    obj = B.new                      #
    obj.protected_mth                # ---> Access is kept within the family. You can specify instance object in defining class and its sub-classes.
    # obj.private_mth       # wrong  #
  end                                #
end                                  #
                                     #
class C                              #
  def test                           #
    a = A.new                        #
    # a.protected_mth       # wrong  #
    # a.private_mth         # wrong  #
  end                                #
end                                  #
                                     #
A.new.test                           #
B.new.test                           #
C.new.test                           #

#+RESULTS:
: A-protected
: A-private
: A-protected
: B-protected
: B-protected
: B-private
: B-protected
: B-protected