0

我想将所有 ruby​​ 文件包含在实现该功能的目录中toto()

在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()
4

1 回答 1

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
于 2013-02-04T19:04:15.043 回答