I would like to do something like this from a Ruby script, within a loop:
- Write a file a.rb (which changes each iteration)
- execute system(ruby 'a.rb')
- a.rb writes a string with results to a file 'results'
- a.rb finishes and Ruby returns 'true' (assuming no errors)
- 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
1 Answer 1
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
-
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 Swoveland2010年08月19日 03:19:15 +00:00Commented 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 toeval
you make.Borealid– Borealid2010年08月19日 03:30:04 +00:00Commented Aug 19, 2010 at 3:30 -
I see lots of ways to break ruby globally, so use eval only for trusted code.akostadinov– akostadinov2015年04月21日 16:43:50 +00:00Commented Apr 21, 2015 at 16:43
lang-rb
a.rb
at all? Why don't you have your main script writeresults
file itself? Where does the code you are writing toa.rb
come from? Does it have to be a string, or it may be code of your main script?