运行 Ruby 任何语言的脚本

Running a script of any language in Ruby

我可以在 Ruby 中执行 shell 命令,使用:

def run(code)
    %x[ #{code} ]
end

我还可以使用 Ruby 评估 Ruby 脚本:

def run(code)
    eval(code)
end

有没有办法将 execute/evaluate code 作为 shell 脚本,而不考虑语言?我正在考虑在 code 的开头包含 #!/bin/bash#!/usr/bin/env ruby,但不确定如何形成字符串并调用它。

but not sure how to form the string and invoke it.

你在 #!/bin/bash#!/usr/bin/env ruby 的正确轨道上,它们指向用于解释代码的二进制文件,但我不确定你是否可以将代码作为string - 您可能需要先将代码保存到一个临时文件中,然后 运行 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"

当然您也可以创建临时文件,将其标记为可执行文件 (chmod),然后直接 运行。那么你的最后一步就不需要指定解释器了:

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

添加shell命令ruby -e.

%x["ruby -e " + code]