sawa
sawa

Reputation: 168081

Inverse of `Module#singleton_class`

What is the inverse of Module#singleton_class? I.e., given a singleton class, how can I get the module it is the singleton of?

Upvotes: 1

Views: 121

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You can use ObjectSpace#each_object for that:

module M; end
sc = M.singleton_class

ObjectSpace.each_object(Module).find { |m| m.singleton_class == sc }
  #=> M

@ndn pointed out that:

ObjectSpace.each_object(sc).to_a #=> [M]

so it's just:

ObjectSpace.each_object(sc).first #=> M

Upvotes: 7

Related Questions