2013-02-04 35 views
0

我想将所有ruby文件包含在实现函数toto()的目录中。如何动态包含ruby文件

在Python中我会做:

res = [] 
for f in glob.glob("*.py"): 
    i = __import__(f) 
    if "toto" in dir(i): 
    res.append(i.toto) 

,我可以用列表如下:

for toto in res: 
    toto() 

回答

2

在Ruby进口比Python中非常不同的 - 在Python文件和模块更或者更少一些,在Ruby中他们不是。你必须手动创建模块:

res = [] 
Dir.glob("*.rb") do |file| 
    # Construct a class based on what is in the file, 
    # and create an instance of it 
    mod = Class.new do 
    class_eval File.read file 
    end.new 

    # Check if it has the toto method 
    if mod.respond_to? :toto 
    res << mod 
    end 
end 

# And call it 
res.each do |mod| 
    mod.toto 
end 

或者更多的Ruby成语:

res = Dir.glob("*.rb").map do |file| 
    # Convert to an object based on the file 
    Class.new do 
    class_eval File.read file 
    end.new 
end.select do |mod| 
    # Choose the ones that have a toto method 
    mod.respond_to? :toto 
end 

# Later, call them: 
res.each &:toto