如何像 shell 那样分割字符串来填充 ARGV?

发布于 2024-11-08 18:29:06 字数 811 浏览 0 评论 0原文

我想要一个 Ruby 方法或一个正则表达式,它可以让我将命令行参数字符串拆分为类似 ARGV 的数组。我要问的问题与这个问题类似,但是是在Ruby中。

我正在为一个 Ruby 程序编写单元测试,该程序使用 Trollop 处理命令行输入(尽管这个问题对于任何其他选项解析器来说都是相同的)。

我想要测试的方法如下所示:

def parse_args(args)
  Trollop::options(args) do
    # ... parse options based on flags
  end
end

在我的程序中,我调用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\""]

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\""]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清晨说晚安 2024-11-15 18:29:06

如果您使用的是 1.9,则有 Shellwords。如果您没有使用 1.9,但有 Rails,那么您将从 Rails 获得 Shellwords 。无论哪种情况,您都可以使用 Shellwords.shellwords 像 POSIX shell 一样解析字符串:

>> Shellwords.shellwords("Where is 'pancakes house'?")
=> ["Where", "is", "pancakes house?"]

如果您没有 Rails 或 1.9,那么您可能只需获取 shellwords.rb< /code> 来自 Rails 并使用它。

更新:它看起来像Shellwords在 Ruby 1.8 中可用(谢谢 Michael Khol)。我得到了关于哪些特定版本拥有它的模糊结果。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文