Skip to content

Instantly share code, notes, and snippets.

@khiet
Last active May 3, 2021 06:54
Show Gist options
  • Save khiet/44f84f4e054fb7d9cc17acf9c38f0c19 to your computer and use it in GitHub Desktop.
Save khiet/44f84f4e054fb7d9cc17acf9c38f0c19 to your computer and use it in GitHub Desktop.
private and protected in Ruby
class A
def public_message
protected_message
end
def self_protected_message
self.protected_message
end
def self_private_message
self.private_message
end
protected
def protected_message
puts "Protected message"
end
private
def private_message
puts "Private message"
end
end
class B < A
def a_protected_message
protected_message
end
def a_private_message
private_message
end
def b_instance_protected_message
B.new.protected_message
end
def b_instance_private_message
B.new.private_message
end
def a_instance_protected_message
A.new.protected_message
end
def a_instance_private_message
A.new.private_message
end
end
class C
def a_instance_protected_message
A.new.protected_message
end
def a_instance_private_message
A.new.private_message
end
end
A.new.public_message
A.new.self_protected_message
A.new.self_private_message
# A.new.protected_message # protected method `protected_message' called for #<A:0x00007f9f21935a18> (NoMethodError)
# A.new.private_message # private method `private_message' called for #<A:0x00007fd449061718> (NoMethodError)
B.new.a_protected_message
B.new.a_private_message
B.new.b_instance_protected_message
# B.new.b_instance_private_message # private method `private_message' called for #<B:0x00007f84f003d6e0> (NoMethodError)
B.new.a_instance_protected_message
# B.new.a_instance_private_message # private method `private_message' called for #<A:0x00007f9cc2935240> (NoMethodError)
# C.new.a_instance_protected_message # protected method `protected_message' called for #<A:0x00007fa6d006d208> (NoMethodError)
# C.new.a_instance_private_message # private method `private_message' called for #<A:0x00007fce2d8a92f8> (NoMethodError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment