Reading — step 1 of 5
Learn
~1 min readSingletons and Reflection
In Ruby, you can attach a method to a SINGLE object instance:
s = "hello"
def s.shout
upcase + "!"
end
s.shout # "HELLO!"
"world".shout # NoMethodError — only s has it
These are singleton methods. Behind the scenes, Ruby creates a hidden class — the eigenclass (also called singleton class or metaclass) — that lives between the object and its real class.
Lookup order for obj.method:
- obj's eigenclass
- obj's class
- obj's class's mixins
- obj's class's parent
- ...up to BasicObject
- method_missing fallback
Class methods are singleton methods on the class object:
class User
def self.find(id) # "def self.x" defines a singleton on User
# ...
end
end
# Equivalent:
User.singleton_class.define_method(:find) do |id|
# ...
end
class << obj syntax opens the eigenclass:
class User
class << self # opens User's eigenclass — i.e., "all class methods"
def find(id)
# ...
end
def create(attrs)
# ...
end
end
end
Clean way to declare multiple class methods in one block.
Use cases:
- Class methods (Ruby's static methods)
- Per-instance customization (rare in app code, common in test mocks)
Object#extendadds module methods to a single instance:
module Greeter
def hello; "hi #{name}"; end
end
user = User.new(name: "Ada")
user.extend(Greeter)
user.hello # "hi Ada"
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…