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

Borealid
99.2k9 gold badges111 silver badges123 bronze badges
asked Aug 19, 2010 at 3:07
3
  • Related question: Running another ruby script from a ruby script Commented Aug 19, 2010 at 3:16
  • Why do you need a.rb at all? Why don't you have your main script write results file itself? Where does the code you are writing to a.rb come from? Does it have to be a string, or it may be code of your main script? Commented Aug 19, 2010 at 8:20
  • Thank you, Mladen. Sorry for taking so long to get back. The main program is constructing Ruby programs (in a loop), which it stores in an array of strings (or one long string). It then needs to direct Ruby to run each of these programs. The results file was simply a brute force way for each of the constructed programs to send its results back to the main program. Commented Aug 20, 2010 at 4:44

1 Answer 1

3

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

answered Aug 19, 2010 at 3:09
3
  • 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. Commented Aug 19, 2010 at 3:19
  • @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. Commented Aug 19, 2010 at 3:30
  • I see lots of ways to break ruby globally, so use eval only for trusted code. Commented Apr 21, 2015 at 16:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.