I can execute shell command in Ruby using:
def run(code)
%x[ #{code} ]
end
I can also evaluate Ruby script in Ruby using:
def run(code)
eval(code)
end
Is there a way to blindly execute/evaluate code
as a shell script, regardless of the language? I'm thinking of including #!/bin/bash
or #!/usr/bin/env ruby
at the beginning of code
, but not sure how to form the string and invoke it.
You're on the right track with
#!/bin/bash
and#!/usr/bin/env ruby
which point to the binaries used to interpret the code, but I'm not sure if you can pass in the code as a string - you might need to save the code to a temporary file first, and then run it:Of course you could also create the temp file, mark it as executable (chmod), and just run it directly. Then your last step wouldn't need the interpreter specified: