Equivalent to Python's dynamic import statement in Ruby?

拈花ヽ惹草 提交于 2020-01-04 07:45:11

问题


In python, to dynamically load a module, you can simply use the _____import_____ statement and assign the module to a variable, I.e(from the docs):

spam = __import__('spam', globals(), locals(), [], -1)

I have used this several times in python in order to simulate dynamic module loading/unloading, because to "unload" the module, you can simply remove all references to it, I.e:

spam = None

Is there an equivalent to this in Ruby? I looked at a few other questions (this, this, and this), but I wanted to know a way to constrain a loaded module to a variable, if possible.


回答1:


Does this do what you want?

require 'bigdecimal/math' # a module from stdlib
bm = BigMath # a module is just an object
BigMath = nil # yields a warning, but BigMath is gone.
puts bm.log(10, 40).to_s # it's alter ego lives.
#=> 0.230258509299404568401799145468436420760110148862877297632502494462371208E1 



回答2:


AFAIK, Ruby doesn't really have the concept of a single export object that a required file could assign to a variable; thus, I don't see how you would do this.

Note, however, that you could still use things like remove_const to undefine classes that have already been loaded.




回答3:


Nah, not possible. If you require or load a file in Ruby, you import the file into the global namespace.



来源:https://stackoverflow.com/questions/8449134/equivalent-to-pythons-dynamic-import-statement-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!