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