在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