Created
December 3, 2013 07:13
-
-
Save sjaveed/7765208 to your computer and use it in GitHub Desktop.
Declaring Private Methods on on a Specific Instance of a Class in Ruby
This file contains 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 Person | |
def name | |
nickname? ? 'Bob' : 'Robert' | |
end | |
def nickname? | |
false | |
end | |
end | |
bob = Person.new | |
# This doesn't throw an exception because public | |
bob.nickname? | |
bob.instance_eval do | |
def nickname? | |
true | |
end | |
end | |
class << bob | |
private :nickname? | |
end | |
# This throws an exception because private | |
bob.nickname? | |
jim = Person.new | |
# This doesn't throw an exception because public. The privacy was only for that instance's nickname? method | |
jim.nickname? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment