2011-01-07 79 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"] 

您可以使用按鍵{}作爲例子,括號[]或甚至還引用了「」以及通過在該空間之前放置反斜槓來避開空格。

相關問題