【问题标题】:How does the .match method work in relation to its args?.match 方法相对于它的 args 是如何工作的?
【发布时间】:2015-01-28 08:19:14
【问题描述】:

我正在通过网站 RubyMonk.com 学习如何使用 Ruby 编程(据我所知,这是一个很棒的网站)。

我在理解 RegEx 的概念以及它如何与 .match 方法一起工作时遇到了一些麻烦。

'RubyMonk Is Pretty Brilliant'.match(/ ./, 9)

.match 中的参数有什么用途?

【问题讨论】:

    标签: ruby methods arguments


    【解决方案1】:

    .match 中的参数有什么用途?

    阅读String#match的文档

    将模式转换为正则表达式(如果它还不是一个),然后在 str 上调用它的 match 方法。 如果存在第二个参数,它指定字符串中开始搜索的位置。

    因此,在您的示例中,#match 将从 10th 字符或 9th 开始其工作位置向前。

    【讨论】:

      【解决方案2】:

      String#match的可选参数是指定搜索开始的起始位置:

      'RubyMonk Is Pretty Brilliant'.match(/ ./, 0)
      # => #<MatchData " I">
      'RubyMonk Is Pretty Brilliant'.match(/ ./, 9)
      # => #<MatchData " P">
      'RubyMonk Is Pretty Brilliant'.match(/ ./, 12)
      # => #<MatchData " B">
      

      【讨论】:

        猜你喜欢
        • 2014-09-24
        • 2015-09-02
        • 2015-07-27
        • 1970-01-01
        • 2013-10-08
        • 2014-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多