Skip to content

Instantly share code, notes, and snippets.

@cheald
Last active August 29, 2015 14:24
Show Gist options
  • Save cheald/17681f00f232016e9123 to your computer and use it in GitHub Desktop.
Save cheald/17681f00f232016e9123 to your computer and use it in GitHub Desktop.
foo = Class.new # You now have an anonymous class, which is just an instance of the Class class.
# instance_exec sets `self` to the given instance (<foo>, in this case, our anonymous class)
# for the duration of the block
foo.instance_exec do
define_method :bar do
"Hello from an instance of foo! I am #{self.inspect}"
end
# Here, we're going to step into <foo>'s metaclass, which is the class which defines singleton instance methods for <foo>
class << self
def baz
"Hi from foo's metaclass, I am #{self.inspect}"
end
end
end
puts foo.baz
puts foo.new.bar
# => Hi from foo's metaclass, I am #<Class:0x649d209a>
# => Hello from an instance of foo! I am #<#<Class:0x649d209a>:0x6adca536>
You can see that <foo> is an instance of the anonymous metaclass <Class:0x649d209a>!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment