2011-01-07 78 views

回答

10

可以使用Shellwords模块从Ruby的标准库,这正是存在这样的目的:

require 'shellwords' 
Shellwords.shellwords 'apple orange "banana pear" pineapple\ apricot' 
#=> ["apple", "orange", "banana pear", "pineapple apricot"] 

正如在上面的例子中可以看出,这也可以让你逃脱用反斜杠空间以同样的方式你可以在shell中。当然,你也可以使用单引号而不是双引号,并用反斜杠将两种引号转义,以得到一个字面的双引号或单引号。

+0

这是非常优雅,我删除我的答案。当我得到更多选票时,我会投票给你。 :) – Phrogz 2011-01-07 21:57:16

1

甚至有一个更清洁的方式做到这一点,你可以用“%W”方式如下:

%w{hello there this is just\ a\ test} 
=> ["hello", "there", "this", "is", "just a test"] 

您可以使用按键{}作为例子,括号[]或甚至还引用了“”以及通过在该空间之前放置反斜杠来避开空格。

相关问题