How to obtain the object corresponding to a given singleton (or eigen) class in Ruby?

StackOverflow https://stackoverflow.com/questions/13552394

  •  02-12-2021
  •  | 
  •  

Question

Suppose the following code:

class A
end

a = A.new

As = class << a
    self
end

# or:
# As = a.singleton_class

Is there some way to get a from As?

Was it helpful?

Solution 2

I think it is simple:

ObjectSpace.each_object(As).first
# => #<A:0x000000029a7c50>

OTHER TIPS

Here's a trick for you:

class A
end

a = A.new

As = a.singleton_class

a2 = ObjectSpace.each_object.select{|obj| obj.singleton_class == As}.first

a2 == a # => true

This is just educated guessification on my part so YMMV, but I think "a" needs to be defined as a class variable (ie. "@@a = A.new") and then you would have the appropriate accessor method to return the class instance.

That being said, however, have you considered using the Singleton module (assuming you're on 1.9.3)?

The solution by sawa does not work for eigenclasses of classes. A universal method can be obtained via Object#to_s and Module#to_s methods, by parsing the returned string, see atalon.cz. However, this solution is not 100% reliable, because in Ruby, constants can be reassigned / deleted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top