Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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"
# 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"
def public_method; 'OK public' end
def protected_method; 'OK protected' end
def private_method; 'OK private' end
# Internal Visibility
puts "\nInternal Visibility / Implicit Receiver"
puts "---------------------------------------"
puts "\nInternal Visibility / Explicit Receiver"
puts "---------------------------------------"
# External Visibility
puts "\nExternal Visibility"
puts "---------------------------------------"
my_instance =
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"
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
You can’t perform that action at this time.