代码之家  ›  专栏  ›  技术社区  ›  johannes

你能告诉我给定的类是否在给定的模块中定义吗

  •  1
  • johannes  · 技术社区  · 16 年前
    Module M
        Class C
        end
    end
    

    我需要的是:

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

    这是否存在?

    我知道我可以解析M::C.name。但有些电子书可能会有改变模块名称的想法,让它更美味或者其他什么。我想要一个干净的解决方案。

    2 回复  |  直到 16 年前
        1
  •  3
  •   sepp2k    16 年前
    M.constants.map {|c| M.const_get(c)}.include?(M::C)
    

    或者,根据johannes的评论,使用find(如果类确实存在于M中,并且不是M中的最后一个常量,那么性能会更好-尽管它很少会产生可测量的差异):

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

    编辑:因为您实际上只需要一个布尔结果,所以 any? 发送的比发送的多 find :

    M.constants.any? {|c| M.const_get(c) == M::C }
    
        2
  •  2
  •   Community Mohan Dere    9 年前

    sepp2k's answer 如果 M::C 根本没有定义,因为Ruby将引发 NameError 在那个街区。

    试试这个:

    M.constants.include?('C')
    

    用不同的名字,就像这样:

    module M
      class C
      end
    end
    
    MY_M_C = M::C
    

    MY_M_C M C

    M.constants.include?('C') ? MY_M_C == M.const_get(:C) : false