Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you parse a string into an array in the way similar to ARGV?

Tags:

ruby

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?

like image 710
dan Avatar asked Dec 21 '22 19:12

dan


2 Answers

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.

like image 183
sepp2k Avatar answered May 11 '23 15:05

sepp2k


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.

like image 35
LuisVM Avatar answered May 11 '23 16:05

LuisVM