views:

65

answers:

1

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.)

+3  A: 

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').

Borealid
Wow, that was fast! Borealid, do you mean eval's argument is a single string containing all the code, with \n at the end of each line of code? I would expect to have the code in an array of strings, though I could of course convert that to a single string.
Cary Swoveland
@Cary Swoveland: How large a single block passed to `eval` is depends on what you're trying to do - the "granularity" of your task. Generally, you should try to minimize the number of distinct calls to `eval` you make.
Borealid