Suppose we have the following Foo
module:
module Foo class Bar end class Tar end module Goo class Bar end end end
If you don't know what classes are in Foo
, you can do the following:
a = ObjectSpace.each_object(Class).with_object([]) { |k,a| a << k if k.to_s.start_with?("Foo::") }
See ObjectSpace :: each_object .
Then you can do what you want with the array a
. Perhaps you want to narrow it down to treasures whose names end in "Bar"
:
b = a.select { |k| k.to_s.end_with?("Bar") }
If you want some of the names to exclude "Foo ::" (although I can't imagine why), this is a simple string manipulation:
b.map { |k| k.to_s["Foo::".size..-1] } #=> ["Goo::Bar", "Bar"]
or
b.map { |k| k.to_s[/(?<=\AFoo::).*/] #=> ["Goo::Bar", "Bar"] }
Please note: there is no Bar
or Goo::Bar
object.
source share