Here’s a brute-force but perhaps useable implementation:
class Class
def single_instance
ObjectSpace.each_object do |obj|
c = (class << obj; self; end)
return obj if c == self
end
end
end
p (class << “hello”; self; end).single_instance # “hello”
In fact, there seems to be an instance variable named “attached”
in singleton classes, that is linked to the instance. It is not
accessible from ruby (because it doesn’t start with “@”); I guess this
is a design decision (?).
I don’t understand this. What should singleton method/attribute return?
As I understand this correctly, init method in this case is a
instance’s method, not a singleton class’s method.
My mistake. I thought “singleton” was the single instance, and
“singleton class” meant “the singleton’s class”. Looking in the
dictionary, I guess the second definition (“a set containing a single
member”) is the correct one, isn’t it?