Categories
Programming

Public, Private, Protected

Quick demonstration of public, private, and protected methods.

public Can be called from anywhere – inside or outside the class.
protected Can be called from within the class, either by the object itself or by another object that is the same class.
private Can only be called by other methods of the same object (not by another object even if it is the same class).
class Earth
 attr_accessor :myAttribute
 
 def hello
  bananna
  cherry
 end
 
 def goodbye(the_other_object)
  the_other_object.apple
  the_other_object.bananna # yes, you can call the protected method bananna on another object of the class
  
  begin
   the_other_object.cherry
  rescue StandardError => theError
   #
   puts “you can’t call the private method of another object even if it is the same class! #{theError}”
  end
 end
 
 public  # declaration not needed, just shown for clarity
  def apple
   puts “Someone called apple for #{@myAttribute} … anyone can call me”
  end

 protected
  def bananna
   puts “Someone called bananna for #{@myAttribute} … only this class may call me”
  end

 private
  def cherry
   puts “Someone called cherry for #{@myAttribute} … only other methods of this instance may call me”
  end
end

Now, in IRB, try this:

>> a = Earth.new
=> #<Earth:0x105107650>
>> a.myAttribute = “object A”
=> “object A”
>> a.apple
Someone called apple for object A anyone can call me
=> nil
>> a.hello
Someone called bananna for object A only this class may call me
Someone called cherry for object A only other methods of this instance may call me
=> nil
>> b = Earth.new
=> #<Earth:0x1050f50e0>
>> b.myAttribute = “object B”
=> “object B”
>> b.apple
Someone called apple for object B anyone can call me
=> nil
>> b.goodbye(a)
Someone called apple for object A anyone can call me
Someone called bananna for object A only this class may call me
you can’t call the private method of another object even if it is the same class! private method `cherry’ called for #<Earth:0x105107650 @myAttribute=”object A”>
=> nil

I know this is a little bit of a brain-bender but if you grok this then you grok public, private, protected.

Leave a Reply

OR LOG IN WITH




Your email address will not be published. Required fields are marked *