Created
March 20, 2012 04:42
-
-
Save jish/2131424 to your computer and use it in GitHub Desktop.
Private vs. Protected in Ruby
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 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