Ruby : Public , Private, Protected simplified

My Daily Technical Notes [ Ruby, Rails, Gems, Server Ops]

class A
  privatedef pri
    'hey I am private of A'
  endprotecteddef prot
    'Hey I am protected of A'
  endendclass B < A
  def call_pri_of_a
    pri
  enddef call_prot_of_a
    prot
  endend

Now calling the accessors within B

 > b = B.new=> #<B:0x00000002b56ad8> 
 > b.call_pri_of_a
 => "hey I am private of A" 
 > b.call_prot_of_a
 => "Hey I am protected of A"

Up to here; there seem to be no difference

bb = B.new=> #<B:0x00000002b1a0b0>
def bb.access_private(child_of_B)
  child_of_B.pri
end
def bb.access_protected(child_of_B)
  child_of_B.prot
end

Now calling the accessor

> bb.access_private(b)
# => NoMethodError: private method `pri' called for #<B:0x00000002b56ad8>
> bb.access_protected(b)
# => "Hey I am protected of A"

View original post

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s