Is there a way of checking whether an object has a singleton class without creating one?
Other than stated in Check if an object has a singleton class, it is not true that every object has a singleton class (see proof under https://repl.it/DuVJ/2).
The following approaches came into my mind, but don't work:
obj.singleton_class
This automatically creates a new singleton class if none exists (see https://ruby-doc.org/core-1.9.2/Object.html#method-i-singleton_class).
Using
ObjectSpace
:has_singleton_class = ObjectSpace.each_object(Class).any? do |klass| klass < self.class && klass.singleton_class? && self.is_a?(klass) end
This is very slow and might not work under jRuby as
ObjectSpace
might not be available.obj.singleton_methods
only works if the singleton class has at least one method.