Skip to content

Instantly share code, notes, and snippets.

@sjaveed
Created December 3, 2013 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjaveed/7765208 to your computer and use it in GitHub Desktop.
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
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