Skip to content

Instantly share code, notes, and snippets.

@satriahrh
Created February 4, 2020 15:42
Show Gist options
  • Save satriahrh/4d4a8018acc0e1624e2193042d190792 to your computer and use it in GitHub Desktop.
Save satriahrh/4d4a8018acc0e1624e2193042d190792 to your computer and use it in GitHub Desktop.
public vs private vs protected in Ruby
class A
def test
self.call_private("A") rescue p 'cannot call self.call_private("A")'
call_private("A")
call_protected("A")
self.call_protected("A")
end
protected
def call_protected(from)
p "protected call from #{from}"
end
private
def call_private(from)
p "private call from #{from}"
end
end
class AB < A
end
class AC < A
def test
self.call_private("AC") rescue p 'cannot call self.call_private("AC")'
call_private("AC")
call_protected("AC")
self.call_protected("AC")
ab = AB.new
ab.call_protected("AC")
ab.call_private("AC") rescue p 'cannot call ab.call_private("AC")'
end
end
class B
def test
a = A.new
a.test
a.call_protected("B") rescue 'cannot call a.call_protected("B")'
a.call_private("B") rescue 'cannot call a.call_private("B")'
ac = AC.new
ac.test
ac.call_protected("AC") rescue 'cannot call ac.call_protected("AC")'
ac.call_private("AC") rescue 'cannot call ac.call_private("AC")'
end
end
B.new.test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment