“Module#singleton_class”的反向 [英] Inverse of `Module#singleton_class`

查看:117
本文介绍了“Module#singleton_class”的反向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Module#singleton_class 的逆是什么?对我有用[0]丢个板砖[0]引用回复举报|收藏| 3楼|打赏|回复|评论楼主: =http://ruby-doc.org/core-2.2.0/ObjectSpace.html#method-c-each_object =nofollow> ObjectSpace#each_object :

 模块M; end 
sc = M.singleton_class

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

编辑:@ndn指出:

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

因此只是:

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


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?

解决方案

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

Edit: @ndn has pointed out that:

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

so it's just:

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

这篇关于“Module#singleton_class”的反向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆