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.
我想要一个Ruby方法或一个正则表达式,让我将一串命令行参数拆分成一个类似ARGV的数组。我问的问题类似于这个问题,但在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).
我正在为使用Trollop处理命令行输入的Ruby程序编写单元测试(尽管这个问题对于任何其他选项解析器都是相同的)。
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:
在我的程序中,我调用parse_args(ARGV)。在我的测试中,我认为我可以在空格中传递一个字符串,但这不是ARGV的行为。比较以下内容:
./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\""]
1 个解决方案
#1
11
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:
如果您使用1.9,则有Shellwords。如果您没有使用1.9但确实有Rails,那么您将从Rails获得Shellwords。在任何一种情况下,您都可以使用Shellwords.shellwords来解析像POSIX shell这样的字符串:
>> 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.
如果你没有Rails或1.9那么你可能只是从Rails中获取shellwords.rb并使用它。
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.
更新:看起来Shellwords在Ruby 1.8中可用(谢谢Michael Khol)。关于哪些特定版本有它,我得到了模棱两可的结果。
#1
11
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:
如果您使用1.9,则有Shellwords。如果您没有使用1.9但确实有Rails,那么您将从Rails获得Shellwords。在任何一种情况下,您都可以使用Shellwords.shellwords来解析像POSIX shell这样的字符串:
>> 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.
如果你没有Rails或1.9那么你可能只是从Rails中获取shellwords.rb并使用它。
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.
更新:看起来Shellwords在Ruby 1.8中可用(谢谢Michael Khol)。关于哪些特定版本有它,我得到了模棱两可的结果。