0

I want to include all the ruby files in a directory that implement the function toto().

In python I will do:

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

and I could use the list like this:

for toto in res:
  toto()

1 Answer 1

2

In Ruby imports are very different than in Python - in Python files and modules are more or less the same thing, in Ruby they are not. You'll have to create your modules manually:

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

Or maybe more Ruby idiomatic:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.