Better Know a Ruby Thing: Singleton Classes
5 comments
·January 27, 2025xutopia
I love it when someone dives a bit deeper behind something pretty common for most Ruby devs. It's actually a really elegant pattern that is used and it's everywhere in Ruby.
lcnPylGDnU4H9OF
> There are at least three ways to define a method in a Ruby singleton class.
It's worth noting that two of such ways will, perhaps unintuitively, ignore the `private` keyword.
private
def self.foo
# ...
end
def x.foo
# ...
end
That will define a public method `:foo` on each of `self`'s and `x`'s singleton classes. If you want the method to be private, either 1) explicitly make the method private using `Class#private` or `Class#private_class_method` or 2) use the `class << self` (or `class << x`) syntax in order for the `private` keyword to work as expected. private_class_method def self.foo
# ...
end
def self.foo
# ...
end
private_class_method :foo # `def` will return a symbol of the defined method name so the above syntax is usually sufficient.
def x.foo
# ...
end
x.singleton_class.send :private, :foo # Class#private is a private method(!) so must be called using Object#send.
class << x
private
def foo
# ...
end
end
> The eternal question… Why is Ruby like this?Joy! :) I'm pretty sure matz would agree.
corytheboyd
Went in expecting a basic how-to about the Singleton module, but this is so much more, you clearly know your shit, and I love deep dives like this!
null
[deleted]
I haven't written any ruby for over a decade and a half, when ruby 2.x was still on the horizon. But I do know the source of "eigenclass". It was first jokingly used in an odd instructional programming book / web comic / experimental art piece by "why the lucky stiff" who was briefly prominent in ruby-land then erased himself from the internet. It's funny that it has now become an established term of art for Ruby people.