I want either a Ruby method or a regular expression that will let me split a string of command-line arguments into an ARGV-like array. What I am asking is similar to this question, but in Ruby.
I'm writing unit tests for a Ruby program that processes command-line input using Trollop (though this question would be the same for any other option parser).
The method I want to test looks like this:
def parse_args(args)
Trollop::options(args) do
# ... parse options based on flags
end
end
In my program, I call parse_args(ARGV)
. In my test, I thought I could just pass in a string split on spaces, but this is not the behavior of ARGV. Compare the following:
./argv_example.rb -f -m "Hello world" --extra-args "-vvv extra verbose"
=> ["-f", "-m", "Hello world", "--extra-args", "-vvv extra verbose"]
'-f -m "Hello world" --extra-args "-vvv extra verbose"'.split
=> ["-f", "-m", "\"Hello", "world\"", "--extra-args", "\"-vvv", "extra", "verbose\""]
There is Shellwords if you're using 1.9. If you're not using 1.9 but do have Rails then you'll get Shellwords from Rails. In either case, you can use Shellwords.shellwords
to parse a string like a POSIX shell does:
>> Shellwords.shellwords("Where is 'pancakes house'?")
=> ["Where", "is", "pancakes house?"]
If you don't have Rails or 1.9 then you could probably just grab the shellwords.rb
from Rails and use it.
Update: It looks like Shellwords is available in Ruby 1.8 (thank you Michael Khol). I was getting ambiguous results about which specific versions had it.
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