【问题标题】:How to split each 2 word in string into array - Ruby?如何将字符串中的每个 2 个单词拆分为数组 - Ruby?
【发布时间】:2021-10-27 01:23:25
【问题描述】:

我想将一个字符串拆分为一个数组,其中包含原始字符串的每个 2 个单词,如下所示:

Ex:
str = "how are you to day"
output = ["how are", "are you", "you to", "to day"]

任何人都可以提供解决方案?非常感谢!

【问题讨论】:

标签: ruby-on-rails ruby string split


【解决方案1】:

这是一种方法,它使用正则表达式技巧来复制输入字符串中倒数第二个单词:

input = "how are you to day"
input = input.gsub(/(?<=\s)(\w+)(?=\s)/, "\\1 \\1")
output = input.scan(/\w+ \w+/).flatten
puts output

打印出来:

how are
are you
you to
to day

【讨论】:

    【解决方案2】:

    输入

    str = "how are you to day"
    

    代码

    p str.split(/\s/)
         .each_cons(2)
         .map { |str| str.join(" ") }
    

    输出

    ["how are", "are you", "you to", "to day"]
    

    【讨论】:

    • “map(:&itself)”和调用“to_a”基本一样吗?
    • @melcher 不! map(&amp;:itself) = map{|x| x}
    • 对于给出的示例,split 参数并不是真正必要的。
    • split 返回一个数组。如果将str.split(/\s/)(或只是str.split)替换为gsub(/\w+/),则可以通过返回枚举数来节省内存。
    • @Rajagopalan,不客气。完全没有反对您建议的方法,但就其价值而言,我在下面发布的替代方法比在您建议的方法中使用 str.split 快约 20%。
    【解决方案3】:

    这是另一种选择:

    str = "how are you to day"
    arr = str.split
    new_arr = []
    (arr.length-1).times {new_arr.push(arr[0..1].join(" ")); arr.shift}
    
    print new_arr #=> ["how are", "are you", "you to", "to day"]
    

    【讨论】:

    • ...或删除 new_arr = [] 并将下一行替换为 (arr.length-1).times.map { |i| arr[i] + ' ' + arr[i+1] }
    【解决方案4】:

    这里有几种方法可以做到这一点。两者都使用String#gsub 的形式,它接受一个正则表达式作为它的参数并且没有块,返回一个枚举数。这种形式的gsub 只生成正则表达式的匹配;它与字符串替换无关。

    str = "how are you to day"
    

    使用包含肯定前瞻的正则表达式

    r = /\w+(?=( \w+))/
    str.gsub(r).with_object([]) { |s,a| a << s + $1 }
      #=> ["how are", "are you", "you to", "to day"]
    

    我已将枚举器 str.gsub(r) 链接到 Enumerator#with_object。当正则表达式包含捕获组时,String#gsubString#scan 的便捷替代品。有关它如何处理捕获组的说明,请参阅 String#scan

    我们可以在free-spacing模式中编写正则表达式以使其自文档化。

    r = /
        \w+       # match >= 1 word characters
        (?=       # begin a positive lookahead
          ( \w+)  # match a space followed by >= 1 word characters and save
                  # to capture group 1
        )         # end positive lookahead
        /x        # invoke free-spacing regex definition mode
    

    枚举字符串中的连续单词对

    enum = str.gsub(/\w+/)
    loop.with_object([]) do |_,a|
      a << enum.next + ' ' + enum.peek
    end
      #=> ["how are", "are you", "you to", "to day"]
    

    Enumerator#nextEnumerator#peek。在next 返回字符串中的最后一个单词之后,peek 引发了一个StopIteration 异常,该异常由loop 通过跳出循环并返回数组a 来处理。见Kernel#loop

    【讨论】:

    • 你是真正的 Ruby 大师!
    • @Rajagopalan,谢谢,但你被误导了!我只是一个 Ruby 爱好者。
    • 这就是为什么你更有效率!
    猜你喜欢
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2011-10-23
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多