Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string likes shells do to populate ARGV?

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\""]
like image 286
Ryan Avatar asked May 20 '11 05:05

Ryan


1 Answers

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.

like image 167
mu is too short Avatar answered Nov 09 '22 22:11

mu is too short