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

I need to rotate a string such as:

'apple orange "banana pear"' 

into an array like this

 ["apple", "orange", "banana pear"] 

This is similar to how command line arguments are converted to an ARGV array. What is the best way to do this in Ruby?

+4
source share
2 answers

You can use the Shellwords module from the standard ruby ​​library, which exists for this very purpose:

 require 'shellwords' Shellwords.shellwords 'apple orange "banana pear" pineapple\ apricot' #=> ["apple", "orange", "banana pear", "pineapple apricot"] 

As you can see from the above example, this also avoids spaces with backslashes just like you can in a shell. And of course, you can use single quotes instead of double quotes and escape both kinds of backslash quotes to get a literal double or single quote.

+10
source

There is an even cleaner way to do this, you can use "% w" as follows:

 %w{hello there this is just\ a\ test} => ["hello", "there", "this", "is", "just a test"] 

You can use the {} keys, as in the example, the brackets [], or even the quotation marks "" , and also avoid spaces by placing a backslash in front of the space.

+1
source

Source: https://habr.com/ru/post/1334714/


All Articles