Created
August 6, 2015 00:03
-
-
Save davidbegin/a12017d76c206468b870 to your computer and use it in GitHub Desktop.
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 | |
# We all know this is for putting "class methods" | |
# on a class | |
# | |
# but this is actually a special syntax for moving into the scope | |
# of a singleton class | |
# | |
# in this case we are moving into the scope of self's singleton's | |
# class | |
# | |
# which in this case is Person | |
class << self | |
end | |
end | |
# but we don't need to always do self, | |
# we can access the singleton class of any object | |
person = Person.new | |
class << person | |
def hello | |
puts "hello from an instance of Person's singleton class!" | |
end | |
end | |
person.hello | |
person2 = Person.new | |
begin | |
person2.hello | |
rescue NoMethodError | |
puts "Sorry person2 does not know about methods on Person's singleton class" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment