Skip to content

Instantly share code, notes, and snippets.

@jish
Created March 20, 2012 04:42
Show Gist options
  • Select an option

  • Save jish/2131424 to your computer and use it in GitHub Desktop.

Select an option

Save jish/2131424 to your computer and use it in GitHub Desktop.
Private vs. Protected in Ruby
class Foo
protected
def protected_method
puts "protected method"
end
private
def private_method
puts "private method"
end
end
class Bar < Foo
def call_protected_method
protected_method
end
def call_private_method
private_method
end
def call_protected_method_with_self
self.protected_method
end
def call_private_method_with_self
self.private_method
end
end
# Bar.new.protected_method # => NoMethodError: protected method ‘protected_method’ called for #<Bar:0x1022bb968>
# Bar.new.private_method # => NoMethodError: private method ‘private_method’ called for #<Bar:0x1022bb968>
Bar.new.call_protected_method # => "protected method"
Bar.new.call_private_method # => "private method"
Bar.new.call_protected_method_with_self # => "protected method"
# Bar.new.call_private_method_with_self # => NoMethodError: private method ‘private_method’ called for #<Bar:0x1022bb0f8>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment