2013-06-26 39 views
5

我爲一個項目製作了一個簡單的shell,並且我想讓參數字符串像在Bash中一樣被解析。如何在Ruby中分割參數字符串Bash風格?

foo bar "hello world" fooz 

應該改爲:

["foo", "bar", "hello world", "fooz"] 

等。目前我一直在使用CSV::parse_line,列分隔符設置爲" ".compact荷蘭國際集團輸出。問題是我現在必須選擇是否要支持單引號或雙引號。 CSV不支持多個分隔字符。

Python有正是這種所謂的shlex模塊:

>>> shlex.split("Test 'hello world' foo") 
['Test', 'hello world', 'foo'] 
>>> shlex.split('Test "hello world" foo') 
['Test', 'hello world', 'foo'] 

是否有任何內置隱藏在Ruby中的模塊,可以做到這一點?任何解決方案的建議,將不勝感激。

+1

當然有:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html#method -C-shellsplit。 :) – squiguy

回答

8

Ruby有模塊Shellwords

require "shellwords" 

Shellwords.shellsplit('Test "hello world" foo') 
# => ["Test", "hello world", "foo"] 

'Test "hello world" foo'.shellsplit 
# => ["Test", "hello world", "foo"] 
+0

我相信這是'shellsplit',你擊敗了我! – squiguy

+0

@squiguy'Shellwords#split'是'Shellwords#shellsplit'的別名。 – toro2k

+2

導入「shellwords」後,你也可以做「測試」hello world「foo'.shellsplit」 – Hubro