I need to turn a string such as this:
'apple orange "banana pear"'
把它转换成这样的数组
["apple", "orange", "banana pear"]
这就像命令行参数被转换成ARGV数组的方式。在Ruby中,最好的方法是什么?
I need to turn a string such as this:
'apple orange "banana pear"'
["apple", "orange", "banana pear"]
这就像命令行参数被转换成ARGV数组的方式。在Ruby中,最好的方法是什么?
你可以使用 Ruby 标准库中的 Shellwords
模块来完成此任务:
require 'shellwords'
Shellwords.shellwords 'apple orange "banana pear" pineapple\ apricot'
#=> ["apple", "orange", "banana pear", "pineapple apricot"]
正如上面的示例所示,这也允许您像在shell中一样使用反斜杠来转义空格。当然,您也可以使用单引号而不是双引号,并使用反斜杠转义两种类型的引号以获取文字上的双引号或单引号。
甚至有一种更简洁的方法来做到这一点,你可以这样使用 "%w":
%w{hello there this is just\ a\ test}
=> ["hello", "there", "this", "is", "just a test"]
您可以使用键{},例如括号[]或者引号"",并且通过在空格前加上反斜杠来转义空格。