Can tell ruby me if a given class wass defined in

2019-06-08 14:14发布

Module M
    Class C
    end
end

What I need is something like:

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

Does this exists somehow?

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-08 14:38
M.constants.map {|c| M.const_get(c)}.include?(M::C)

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 }

Edit: 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 }
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-08 14:41

sepp2k's answer won't work if M::C is not defined at all, since Ruby will raise a NameError in that block.

Try this:

M.constants.include?('C')

If you're worried that you have a reference to M::C by a different name, like so:

module M
  class C
  end
end

MY_M_C = M::C

then you can test whether MY_M_C is the same as M's C like so:

M.constants.include?('C') ? MY_M_C == M.const_get(:C) : false 
查看更多
登录 后发表回答