我需要转换一个这样的字符串:
'apple orange "banana pear"'
进入像这样的数组
["apple", "orange", "banana pear"]
这就像命令行参数转换为ARGV数组的方式。在Ruby中执行此操作的最佳方法是什么?
答案 0 :(得分:10)
您可以使用ruby标准库中的Shellwords
模块,该模块完全用于此目的:
require 'shellwords'
Shellwords.shellwords 'apple orange "banana pear" pineapple\ apricot'
#=> ["apple", "orange", "banana pear", "pineapple apricot"]
从上面的示例中可以看出,这也允许您以与shell中相同的方式使用反斜杠转义空格。当然,您也可以使用单引号而不是双引号,并使用反斜杠转义两种引号,以获得文字的双引号或单引号。
答案 1 :(得分:1)
甚至可以采用更简洁的方法,您可以通过以下方式使用“%w”:
%w{hello there this is just\ a\ test}
=> ["hello", "there", "this", "is", "just a test"]
您可以使用 {} 键,例如括号 [] ,甚至引用“”,并通过放置在空间之前反斜杠。