Skip to content

Instantly share code, notes, and snippets.

@2get
Created June 18, 2014 03:51
Show Gist options
  • Save 2get/c081466ce225a419d0a1 to your computer and use it in GitHub Desktop.
Save 2get/c081466ce225a419d0a1 to your computer and use it in GitHub Desktop.
ruby private and protected
class C1
def method
protected_method
self.protected_method
C1.new.protected_method
private_method
self.private_method rescue puts "ERROR self.private_method #{self.class.name}"
C1.new.private_method rescue puts "ERROR C1.new.private_method #{self.class.name}"
end
protected
def protected_method
puts "#{self.class.name} protected_method"
end
private
def private_method
puts "#{self.class.name} private method"
end
end
class C2 < C1
def method
protected_method
self.protected_method
C1.new.protected_method
C2.new.protected_method
private_method
self.private_method rescue puts 'ERROR self.private_method'
C1.new.private_method rescue puts 'ERROR C1.new.private_method'
C2.new.private_method rescue puts 'ERROR C2.new.private_method'
end
end
c1 = C1.new
puts '----- c1.method -----'
c1.method
puts '----- c1.protected_method -----'
c1.protected_method rescue puts 'ERROR c1.protected_method'
puts '----- c1.private_method -----'
c1.private_method rescue puts 'ERROR c1.private_method'
c2 = C2.new
puts '----- c2.method -----'
c2.method
puts '----- c2.protected_method -----'
c2.protected_method rescue puts 'ERROR c2.protected_method'
puts '----- c2.private_method -----'
c2.private_method rescue puts 'ERROR c2.private_method'
@2get
Copy link
Author

2get commented Jun 18, 2014

----- c1.method -----
C1 protected_method
C1 protected_method
C1 protected_method
C1 private method
ERROR self.private_method C1
ERROR C1.new.private_method C1
----- c1.protected_method -----
ERROR c1.protected_method
----- c1.private_method -----
ERROR c1.private_method
----- c2.method -----
C2 protected_method
C2 protected_method
C1 protected_method
C2 protected_method
C2 private method
ERROR self.private_method
ERROR C1.new.private_method
ERROR C2.new.private_method
----- c2.protected_method -----
ERROR c2.protected_method
----- c2.private_method -----
ERROR c2.private_method

@2get
Copy link
Author

2get commented Jun 18, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment