Running a script of any language in Ruby

99 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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:

require 'tempfile'

code = "#!/bin/bash\necho 'hello world'"
interpreter = code.match(/#!(.*)/)[1]

file = Tempfile.new('foo')
file.write(code)
file.close
%x(#{interpreter} #{file.path})  # prints "hello world"

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:

%x(#{file.path})  # prints "hello world"
0
On

Add the shell command ruby -e.

%x["ruby -e " + code]