Is it possible to do something like this in Ruby:
var_1 = Module
var_2 = NestedModule
object = ::var_1::var_2::SomeObject.new # class resolves to ::Module::NestedModule::SomeObject
Though the above code does not work in Ruby, is there any alternative way to do this or is this not possible?
First off, NestedModule
is a bad name for a variable, in fact, it is actively misleading: the module isn't nested (there are no nested modules in Ruby), it's the constant that is nested.
In fact, that's precisely the confusion that leads to this question.
So, the constant NestedModule
is nested inside the module referenced by the constant Module
, which, however, because of your first line, is also accessible through the local variable var_1
. (Remember, Module
s are objects just like any other object!):
var_1 = Module
To get a reference to NestedModule
in var_2
, you can do:
var_2 = var_1::NestedModule
And lastly, to get a reference to SomeObject
, you can do:
var_2::SomeObject.new
You could do something like this:
klass = Object.const_get("::#{var_1}::#{var_2}::Object")
object = klass.new
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.