Created
September 7, 2018 03:19
-
-
Save yemartin/35dad057d1562dc1c08108fedae120e3 to your computer and use it in GitHub Desktop.
Public, protected and private methods in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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