Created
April 29, 2020 10:09
-
-
Save zsan/ad002caa00d7d0b50848b00e03b62f40 to your computer and use it in GitHub Desktop.
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
class Human | |
def initialize | |
end | |
def name=(name) | |
@name = name | |
end | |
def name | |
@name | |
end | |
# trying to access private method inside the class | |
# will throw an errors | |
# even if we pass `self` as a receiver | |
def proxy_secret | |
self.secret | |
end | |
# the correct way to call private method | |
def access_secret | |
secret | |
end | |
def access_protected_method | |
self.protected_method | |
end | |
private | |
def secret | |
"My Secret" | |
end | |
protected | |
def protected_method | |
"Protected method" | |
end | |
end | |
# private methods can not be called with explicitly defined receiver. | |
# Receiver it's an object on which we call that method. | |
# Even inside a class if we pass self as a receiver that will not work. | |
human = Human.new | |
human.name = 'Foo' | |
puts human.name | |
# puts human.secret # error, private method `secret' called for | |
# puts human.proxy_secret # error, private method `secret' called for | |
puts human.send(:secret) # how we use ruby magic to call private method of the object | |
puts human.access_secret | |
# puts human.protected_method # error protected method `protected_method' called for | |
puts human.access_protected_method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment