Ejemplo de Visibilidad

~/rubytesting/programmingRuby$ !cat
cat -n Visibility.rb 
   1  class Visibility
   2  protected
   3    def tutu_prot
   4      puts "Prot"
   5    end
   6  
   7  private
   8    def tutu_priv
   9      puts "Priv"
  10    end
  11  
  12  public
  13    def tutu_pub
  14      puts "Pub"
  15    end
  16  end
  17  
  18  
  19  class Child < Visibility
  20  
  21    def chachi
  22      puts "in chachi"
  23      self.tutu_prot
  24    end
  25  
  26    def chuchu
  27      puts "in chuchu"
  28      self.tutu_priv
  29    end
  30  end
  31  
  32  if $0 == __FILE__
  33    b = Child.new
  34    b.tutu_pub       # <- Pub
  35    begin
  36      b.tutu_priv    # Exception <NoMethodError> raised <private method `tutu_priv' called for #<Child:0x100168068>> 
  37    rescue NoMethodError
  38        puts "Exception <#{$!.class}> raised <#{$!}>"
  39    end
  40    b.chachi  # <- in chachi
  41              #    Prot
  42    begin
  43      b.chuchu # <- Exception <NoMethodError> raised <private method `tutu_priv' called for #<Child:0x100168068>>
  44    rescue
  45        puts "Exception <#{$!.class}> raised <#{$!}>"
  46    end
  47  
  48    begin
  49      c = Visibility.new
  50      c.tutu_pub  # <- Pub
  51      c.tutu_prot # <- Exception <NoMethodError> raised <protected method `tutu_prot' called for #<Visibility:0x100167b40>>
  52    rescue NoMethodError
  53        puts "Exception <#{$!.class}> raised <#{$!}>"
  54    end
  55  end



Casiano Rodriguez León 2015-01-07