alexandernst
alexandernst

Reputation: 15099

Creating a class namespace from a variable

Is there a way I can compose a class namespace from a variable?

For example, let's say I want to catch an exception that is inside Foo::Bar::MyException, but Bar is in a variable (a = :Bar).

Would that be something like Foo::@a::MyException?

Upvotes: 0

Views: 414

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

Yes, you can do this

Foo.const_get(@a)::MyException

Upvotes: 4

djaszczurowski
djaszczurowski

Reputation: 4515

yes, you can:

module A
  module B
    class C
      def foo
        "bar"
      end
    end
  end
end

variable = "B"
c_instance = Object.const_get("A::#{variable}::C").new
puts c_instance.foo

Upvotes: 2

Related Questions