Skip to content

Instantly share code, notes, and snippets.

@davidbegin
Created August 6, 2015 00:03
Show Gist options
  • Save davidbegin/a12017d76c206468b870 to your computer and use it in GitHub Desktop.
Save davidbegin/a12017d76c206468b870 to your computer and use it in GitHub Desktop.
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