本文介绍了可以告诉ruby我如果给定的类wass在给定的模块中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

Module M
    Class C
    end
end

我需要的是:

M.was_defined_here?(M::C)
M.classes.include?(M::C)

我知道我可以解析M :: C.name。但有人可能有想法改变模块#名称,使它更more more或某事。我想要一个干净的解决方案。

I know I could parse M::C.name. But someebody could have the idea to change Module#name, to make it more astetic or something. I want a clean solution.

推荐答案

M.constants.map {|c| M.const_get(c)}.include?(M::C)

或者,从johannes'注释,使用find(如果类在M中存在并且不会是M中的最后一个常数,则执行得更好 - 虽然它很少会产生可测量的差异):

Or, from johannes' comment, using find (will perform better if the class does exist in M and doesn't happen to be the last constant in M - though it should rarely make a measurable difference):

M.constants.find {|c| M.const_get(c) == M::C }

编辑:布尔结果,此任何?使得发送比更多发现

Since you actually just want a boolean result, this any? makes more send than find:

M.constants.any? {|c| M.const_get(c) == M::C }

这篇关于可以告诉ruby我如果给定的类wass在给定的模块中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 03:06