Cary Swoveland
Cary Swoveland

Reputation: 110725

What is best way to execute a Ruby program from a Ruby program?

I would like to do something like this from a Ruby script, within a loop:

  1. Write a file a.rb (which changes each iteration)
  2. execute system(ruby 'a.rb')
  3. a.rb writes a string with results to a file 'results'
  4. a.rb finishes and Ruby returns 'true' (assuming no errors)
  5. the calling script reads the file 'results' and takes action.

I expect there are many better ways of doing this. For example, instead of step #2-#5 could I simply load 'a.rb' (within the loop) and invoke one one of its methods? Is there a better way by using eval() or something else? (Gaining an understanding of metaprogramming is on my Ruby to-do list.)

Upvotes: 1

Views: 396

Answers (1)

Borealid
Borealid

Reputation: 98509

I think eval is probably the right solution for dynamically-generated code; that's what it's designed for. Instead of creating a.rb at all, just eval('some-code-that-would-be-in-a.rb').

Upvotes: 3

Related Questions