Skip to content

Instantly share code, notes, and snippets.

@yemartin
Created September 7, 2018 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yemartin/35dad057d1562dc1c08108fedae120e3 to your computer and use it in GitHub Desktop.
Save yemartin/35dad057d1562dc1c08108fedae120e3 to your computer and use it in GitHub Desktop.
Public, protected and private methods in Ruby
# Note about `protected`:
#
# One use case for using `protected` is object comparator methods, where the method
# may need to call protected methods on `self` and another object of the same class.
# But 99% of the time, we don't write object comparator methods, that's why we almost
# Never use `protected`. See:
# See http://tenderlovemaking.com/2012/09/07/protected-methods-and-ruby-2-0.html
class MyClass
# Internal Visibility / Implicit Receiver
def implicit_receiver_calls
puts public_method rescue puts "NG public"
puts protected_method rescue puts "NG protected"
puts private_method rescue puts "NG private"
end
# Internal Visibility / Explicit Receiver
def explicit_receiver_calls
puts self.public_method rescue puts "NG public"
puts self.protected_method rescue puts "NG protected"
puts self.private_method rescue puts "NG private"
end
def public_method; 'OK public' end
protected
def protected_method; 'OK protected' end
private
def private_method; 'OK private' end
end
# Internal Visibility
puts "\nInternal Visibility / Implicit Receiver"
puts "---------------------------------------"
MyClass.new.implicit_receiver_calls
puts "\nInternal Visibility / Explicit Receiver"
puts "---------------------------------------"
MyClass.new.explicit_receiver_calls
# External Visibility
puts "\nExternal Visibility"
puts "---------------------------------------"
my_instance = MyClass.new
puts my_instance.public_method rescue puts "NG public"
puts my_instance.protected_method rescue puts "NG protected"
puts my_instance.private_method rescue puts "NG private"
__END__
Outputs:
Internal Visibility / Implicit Receiver
---------------------------------------
OK public
OK protected
OK private
Internal Visibility / Explicit Receiver
---------------------------------------
OK public
OK protected
NG private
External Visibility
---------------------------------------
OK public
NG protected
NG private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment