Can say ruby ​​me if a specific class has been defined in this module

Module M
    Class C
    end
end

I need something like:

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

Does it somehow exist?

I know I can parse M :: C.name. But someone might have the idea of ​​changing the name of the module # to make it more aesthetic or something else. I want a clean solution.

+1
source share
2 answers
M.constants.map {|c| M.const_get(c)}.include?(M::C)

Or from johannes comment using find (it will work better if the class exists in M ​​and is not the last constant in M, although it rarely needs to make a measurable difference):

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

Edit: since you really just want to get a boolean result, this one any?does more sending than find:

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

sepp2k , M::C , Ruby NameError .

:

M.constants.include?('C')

, M::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 
+2

Source: https://habr.com/ru/post/1790382/


All Articles