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

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

  •  02-12-2021
  •  | 
  •  

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?

有帮助吗?

解决方案 2

I think it is simple:

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top