带有双引号的Ruby shell命令

Ily*_*lya 1 ruby shell

我想在反引号中传递JSON格式的字符串作为脚本参数,例如:

stats = "[[\"25/01/2017 03:15 PST\",
           \"26/01/2017 03:15 PST\",
           \"27/01/2017 03:15 PST\",
           \"28/01/2017 03:15 PST\"]]"

`my_executable_script.js "#{stats}"`
Run Code Online (Sandbox Code Playgroud)

并获得stdout值(这很重要).问题是JSON参数应该使用双引号进行转义,例如:

my_executable_script.js "[[\"25/01/2017 03:15 PST....."
Run Code Online (Sandbox Code Playgroud)

而是my_executable_script.js [[\"25/01/2017 03:15 PST.....]]执行(没有""),这是错误的.我尝试了不同的逃避方式,没有成功.

我不能使用system()方法,因为我需要执行脚本的结果.

Cas*_*per 8

用途Shellwords.escape:

>> require 'shellwords'
>> puts %x|echo #{Shellwords.escape(stats)}|

[["25/01/2017 03:15 PST",
  "26/01/2017 03:15 PST",
  "27/01/2017 03:15 PST",
  "28/01/2017 03:15 PST"]]
Run Code Online (Sandbox Code Playgroud)

  • 我不熟悉`Shellwords`模块.有一篇关于它的信息[这里](https://endofline.wordpress.com/2010/12/14/ruby-standard-library-shellwords/). (2认同)