I need to turn a string such as this:
'apple orange "banana pear"'
into an array like this
["apple", "orange", "banana pear"]
This is like the way command line arguments are converted into the ARGV array. What’s the best way to do this in Ruby?
You can use the
Shellwordsmodule from ruby’s standard library, which exists exactly for this purpose:As can be seen in the example above, this also allows you to escape spaces with backslashes the same way you can in the shell. And of course you can also use single quotes instead of double quotes and escape both kinds of quotes with a backslash to get a literal double or single quote.