3

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?

MMSequeira
  • 61
  • 6

4 Answers4

3

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
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

I think it is simple:

ObjectSpace.each_object(As).first
# => #<A:0x000000029a7c50>
sawa
  • 165,429
  • 45
  • 277
  • 381
0

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)?

mjbraun
  • 117
  • 5
  • I'm talking about Ruby eigenclasses, also known as singleton classes, confusingly. This question is not about the singleton pattern. – MMSequeira Nov 25 '12 at 15:50
0

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.

Community
  • 1
  • 1
paon
  • 378
  • 3
  • 12