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 Shellwords
module from ruby's standard library, which exists exactly for this purpose:
require 'shellwords'
Shellwords.shellwords 'apple orange "banana pear" pineapple\ apricot'
#=> ["apple", "orange", "banana pear", "pineapple apricot"]
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.
There is even a cleaner way to do this, you can use "%w" the following way:
%w{hello there this is just\ a\ test}
=> ["hello", "there", "this", "is", "just a test"]
You can use keys {} as in example, brackets [] or even quotes "" as well and escape spaces by putting a backslash before the space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With